React, getting Uncaught TypeError: Cannot read properties of null (reading "useRef") while using React Router Dom

React, getting Uncaught TypeError: Cannot read properties of null (reading "useRef") while using React Router Dom

我正在做一个 React 项目,一切正常。然后我开始使用 react-router-dom 但路由器不工作。我想转到主屏幕,但它却给我这些错误:

app.js:

import Container from 'react-bootstrap/Container'
import Footer from './components/footer';
import Header from './components/header';
import './index.css';
import {BrowserRouter as Router, Route} from 'react-router-dom'
import HomeScreen from './screens/homeScreen';

function App() {
  return (
    <Router>
      <Header/>
      <main className='py-3'>
        <Container >
        <Route path="/" exact component={HomeScreen} />
        </Container>
      </main>
      <Footer/>
    </Router>
  );
}

export default App;

HomeScreen.js:

import React from 'react'
import products from '../products'
import {Row, Col} from 'react-bootstrap'
import Product from '../components/product'

function homeScreen() {
  return (

    <div>
       <h1>Latest Products</h1>
        <Row>
            {products.map(product =>(
                <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                  <Product product={product} />
                </Col>
            ))}
        </Row>
     
            
    </div>
  )
}

export default homeScreen

我建议尝试这个...首先,将您的 react-router-dom 更新到最新版本。

然后像这样导入路由:

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

现在像这样插入路由组件:

<Container>
  <Routes>
    <Route path="/" exact element={<HomeScreen />} />
  </Routes>
</Container>

A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

  1. 确保您的 Node.js 版本不高于 16.15.0,来自 npmcurrent stable version. It it's the case, delete node_modules folder, package-lock.json file, and downgrade it. For that you could use n 包。
# if one of the commands does not pass, you may need to precede them with sudo
npm i -g n
n stable
  1. Routecomponent 属性 更改为 element 作为 React Router Dom v6 的工作方式,并在使用它(<HomeScreen/> 而不是 HomeScreen):
<Route path="/" exact element={<HomeScreen/>} />
  1. 此外,您还想将 Route 组件包装在 react-router-domRoutes 中,以确保您只为给定的 url:[=38 加载一个元素=]
<Routes>
  <Route path="/" exact element={<HomeScreen/>} />
</Routes>
  1. homeScreen 应该是 HomeScreen,否则不被认为是 React 组件。然后重新开始安装您的软件包和 运行 您的服务器:
npm install
npm start