You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:04