ReactJS中BrowserRouter报错:Invalid hook call问题求助
React "Invalid hook call" 错误排查与修复
问题场景
index.js
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import {BrowserRouter, Routes, Route} from 'react-router-dom'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <BrowserRouter> <Route path="/" exact component={App} /> </BrowserRouter> );
App.js
import './App.css'; import {useState, useEffect} from 'react'; function App() { const [drinks, setDrinks] = useState([]); const fetchData = async () => { const response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list'); const jsondata = await response.json(); console.log(jsondata.drinks); setDrinks(jsondata.drinks); } useEffect(() => { fetchData(); }, []) return ( <div className="App"> <ul> {drinks.map((item, index) => { return <li key={index}><a href="">{item.strCategory}</a></li> })} </ul> </div> ); } export default App;
错误信息
react.development.js:209 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 See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
问题原因
你使用的是react-router-dom v6,但写法沿用了v5及更早版本的API:
- v6中
Route组件必须嵌套在Routes组件内部 - v6移除了
component属性,改用element传递组件实例(需用JSX语法) - v6中
Route默认是精确匹配,不再需要exact属性
旧写法会导致App组件被错误渲染,触发Hook调用规则违反。
修复方案
修改index.js的路由配置,适配v6 API:
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import {BrowserRouter, Routes, Route} from 'react-router-dom'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <BrowserRouter> <Routes> <Route path="/" element={<App />} /> </Routes> </BrowserRouter> );
额外检查项
若修复后仍有问题,排查以下内容:
- 确认
react与react-dom版本一致,且与react-router-domv6兼容(要求react>=16.8.0) - 执行
npm ls react查看依赖树,检查是否存在多份React副本
内容的提问来源于stack exchange,提问作者NewToJS
相关产品推荐
相关产品推荐

