React Router v6的升级带来了许多改进,但同时也需要我们重新审视现有的路由配置。本文将分享v6版本工具链整合方案,包括如何平滑迁移现有应用。
核心变化与迁移要点
v6版本移除了Switch组件,改用Routes,并且所有路由组件都需要包裹在Routes内。同时,useHistory被useNavigate替代,这是最需要关注的变更点。
实际迁移步骤
- 首先安装v6版本:
npm install react-router-dom@latest
- 更新路由配置:
import { Routes, Route, Navigate } from 'react-router-dom';
<Routes>
<Route path="/home" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/*" element={<Navigate to="/home" />} />
</Routes>
- 替换历史API:
// v5
const history = useHistory();
history.push('/new-path');
// v6
const navigate = useNavigate();
navigate('/new-path');
工具链整合建议
建议使用@react-router/devtools进行调试,配合eslint-plugin-react-router进行代码检查,确保迁移过程中的代码质量。

讨论