javascript 未捕获的类型错误:无法读取null的属性(阅读“useRef”)

iovurdzv  于 2023-03-21  发布在  Java
关注(0)|答案(2)|浏览(277)

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

Invalid hook call. Hooks can only be called inside of the body of a function component.
Uncaught TypeError: Cannot read properties of null (reading "useRef")

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
yyyllmsg

yyyllmsg1#

1.首先,查看package.json文件,确保每个使用的库都被列为"dependencies"devDependencies。如果没有,则分别安装它们。
1.其次,确保您的node.js版本不上级最新的recommended版本。如果不降级,您可以使用npmn包:

# if one of the commands does not pass, you may need to use sudo
npm i -g n
n stable
# delete node_modules and start over
rm -rf node_modules
npm install

1.最后,确保所有组件都以大写字母开头,homeScreen应该是HomeScreen。如果您使用的是React Router Dom的6版本,请将Routecomponent属性更改为element

<Route path="/" exact element={<HomeScreen/>} />
5q4ezhmt

5q4ezhmt2#

我建议尝试这个...首先,更新你的react-router-dom到最新版本。
然后像这样导入路由:

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

现在插入routes组件,如下所示:

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

<Route>只能作为<Routes>元素的子元素使用,不能直接呈现。请将<Route> Package 在<Routes>中。

相关问题