React项目中react-router-dom 6.8.1代码无法运行的适配方案咨询
React Router DOM 6.8.1 适配修改方案
你遇到的错误是因为React Router DOM v6对核心API做了重大调整,原v5中的部分组件和钩子已被移除,导致导入了不存在的模块。以下是需要修改的具体部分:
核心修改点
- 替换
<Switch>为<Routes>:v6彻底移除了<Switch>,改用<Routes>作为路由的根容器,它的路由匹配逻辑更精准。 - 更新
<Route>的渲染方式:v6中<Route>不再通过嵌套子组件的方式渲染页面,必须使用element属性传入要渲染的组件。 - 替换
useHistory为useNavigate:v6移除了useHistory钩子,新增useNavigate来处理页面跳转逻辑,调用方式略有变化。
修改后的完整代码
import { useState } from "react"; import { BrowserRouter as Router, generatePath, Routes, // 替换Switch为Routes Route, useNavigate, // 替换useHistory为useNavigate useParams } from "react-router-dom"; const products = [ { id: "1", name: "Product 1" }, { id: "2", name: "Product 2" }, { id: "3", name: "Product 3" } ]; const Products = () => { const { id } = useParams(); console.log(id); return ( <div> <p>Lorem Ipsum</p> <p>Id: {id}</p> </div> ); }; const Home = () => { const [id, setId] = useState(); const navigate = useNavigate(); // 替换useHistory为useNavigate const handleProceed = (e) => { id && navigate(generatePath("/products/:id", { id })); // 用navigate替代history.push }; return ( <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }} > <div> {products.map((product, i) => ( <button key={i} onClick={(e) => { setId(product.id); }} > {product.name} </button> ))} </div> <button onClick={handleProceed} style={{ width: "250px" }}> Click </button> </div> ); }; export default function App() { return ( <div className="App"> <header>Heading</header> <Router> <Routes> {/* 替换Switch为Routes */} <Route path="/products/:id" element={<Products />} /> {/* 使用element属性 */} <Route path="/" element={<Home />} /> {/* 使用element属性 */} </Routes> </Router> </div> ); }
内容的提问来源于stack exchange,提问作者Sougata Mukherjee
相关产品推荐
相关产品推荐

