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

React应用中Switch Router无法正常工作问题求助

解决React Router中Switch组件找不到的问题

问题原因

你安装的是react-router-dom v6版本,该版本已移除Switch组件,取而代之的是Routes组件,因此导入Switch会出现导出项不存在的错误。

解决方案

方案1:升级代码适配v6版本

  1. 修改导入语句,替换Switch为Routes:
// 替换前
import { Switch, Route } from 'react-router-dom';

// 替换后
import { Routes, Route } from 'react-router-dom';
  1. 调整路由组件的写法:将Route的component属性改为element,并传入JSX元素而非组件引用:
// 旧写法(v5)
<Switch>
  <Route path="/home" component={Home} />
  <Route path="/about" component={About} />
</Switch>

// 新写法(v6)
<Routes>
  <Route path="/home" element={<Home />} />
  <Route path="/about" element={<About />} />
</Routes>

方案2:降级到react-router-dom v5(不推荐)

如果暂时不想修改代码,可以安装v5版本:

npm install react-router-dom@5

内容的提问来源于stack exchange,提问作者Priyankara Senarathne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:02:02