React中使用useNavigate钩子触发无效钩子调用错误的排查求助
错误提示
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app
相关代码
import React from "react"; import styles from "./Home.module.css"; import { useNavigate } from "react-router-dom"; import Card from "../../components/shared/Card/Card"; import Button from "../../components/shared/Button/Button"; const Home = () => { const signInLinkStyle = { color: '#0077ff', fontWeight: 'bold', textDecoration: 'none', marginLeft: '10px' } const navigate = useNavigate(); const startRegister = () => { navigate("/authenticate"); } return ( <> <div className={styles.cardWrapper}> <Card title='Welcome to Codershouse!' icon='logo'> <p className={styles.text}> We’re working hard to get Codershouse ready for everyone! While we wrap up the finishing youches, we’re adding people gradually to make sure nothing breaks :) </p> <div> <Button onClick={ startRegister } text="Let's Go"/> </div> <div className={styles.signinWrapper}> <span className={styles.hasInvite}>Have an invite text?</span> </div> </Card> </div> </> ); }; export default Home;
package.json配置
{ "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "react": "^18.2.0", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
错误截图

核心问题与解决步骤
缺少react-router-dom依赖
你的package.json中未安装react-router-dom,但代码中导入了useNavigate。执行以下命令安装依赖:npm install react-router-dom # 或使用yarn yarn add react-router-dom组件未处于Router上下文环境
useNavigate钩子必须在react-router-dom提供的Router组件(如<BrowserRouter>)包裹的组件树中使用。需要在应用入口(如App.js或index.js)添加Router包裹:import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import Home from './components/Home'; // 替换为你的Home组件实际路径 function App() { return ( <Router> <Routes> <Route path="/" element={<Home />} /> {/* 按需添加入其他路由规则 */} </Routes> </Router> ); } export default App;排除其他潜在问题
- 当前package.json中react与react-dom版本均为18.2.0,版本匹配,可排除版本不兼容问题。
- 若以上步骤无效,检查是否存在多个React副本:执行
npm ls react查看依赖树,若有重复版本,删除node_modules和package-lock.json后重新执行npm install。
内容的提问来源于stack exchange,提问作者Nikhil Verma
相关产品推荐
相关产品推荐

