Ali*_*Dev 6 javascript reactjs react-router-dom
我正在开发一个 React 项目,一切正常。然后我开始使用react-router-dom,但路由器不工作。我想进入主屏幕,但它给了我这些错误:
Invalid hook call. Hooks can only be called inside of the body of a function component.
Run Code Online (Sandbox Code Playgroud)
Uncaught TypeError: Cannot read properties of null (reading "useRef")
Run Code Online (Sandbox Code Playgroud)
应用程序.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;
Run Code Online (Sandbox Code Playgroud)
主屏幕.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
Run Code Online (Sandbox Code Playgroud)
首先,查看package.json文件内部,确保每个使用的库都列为"dependencies"或devDependencies。如果没有,请单独安装它们。
在您的情况下,如果您没有看到react-router-dom,请在项目的根文件夹中打开一个终端package.json,然后运行:
npm install react-hook-form
Run Code Online (Sandbox Code Playgroud)
如果问题仍然存在,请确保您的 Node.js 版本不优于最后推荐的版本。如果没有,请将其降级,为此,您可以使用以下中的n包npm:
npm install react-hook-form
Run Code Online (Sandbox Code Playgroud)
最后,确保所有组件都以大写字母开头,HomeScreen而不是homeScreen。如果您使用的是 React Router Dom 的版本,请将component的属性更改Route为:element6
# 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31651 次 |
| 最近记录: |