React中BrowserRouter组件触发Invalid Hook Call Warning问题的排查求助
React中BrowserRouter组件触发Invalid Hook Call Warning问题的排查求助
大家好,我现在遇到一个React的Hook调用错误,控制台一直抛出这个警告:
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:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app
我已经对照这三个常见原因逐一排查过了:检查了React和React DOM的版本是否匹配,确认代码里没有违反Hook规则的写法,也排查过项目里是不是存在多个React副本,但还是找不到问题的根源。目前看起来错误好像和BrowserRouter组件有关,下面是我的完整代码,希望大家能帮我看看哪里出问题了,给点调试或解决的建议,谢谢!
我的项目代码:
import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faImage } from '@fortawesome/free-solid-svg-icons'; import "./App.css"; import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'; const galleryData = [ { id: 1, imageUrl: 'https://images.unsplash.com/photo-1593053109521-e86fd978ba96?q=80&w=1674&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D', title: 'Beautiful Sunset', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', } ]; const Home = () => ( <div className="App"> <Nav /> <div className='heading' style={{ display: "flex" }}> <FontAwesomeIcon icon={faImage} size='lg' /> <h2>Image Gallery</h2> </div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p> <button title='View More'> <Link to="/gallery">See Images</Link> </button> </div> ); const Gallery = () => ( <div className="App"> <Nav /> <div className='heading' style={{ display: "flex" }}> <FontAwesomeIcon icon={faImage} size='lg' /> <h2>Image Gallery</h2> </div> <div className='gallery'> {galleryData.map(item => ( <div key={item.id} className="gallery-item"> <img src={item.imageUrl} alt={item.title} /> <div className="caption"> <h1>{item.title}</h1> <p>{item.description}</p> </div> </div> ))} </div> </div> ); const Nav = () => ( <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/gallery">Gallery</Link> </li> {/* Add more navigation links as needed */} </ul> </nav> ); function App() { return ( <Router> <Routes> <Route path="/" exact component={Home} /> <Route path="/gallery" component={Gallery} /> </Routes> </Router> )}; export default App;
备注:内容来源于stack exchange,提问作者Bilal Raza
相关产品推荐
相关产品推荐

