v6路由参数传递方式变更踩坑指南:使用技巧分享
最近在将项目从React Router v5升级到v6时,遇到了一个让人头疼的问题——路由参数传递方式发生了重大变更。本文记录了我在升级过程中遇到的踩坑经历和解决方案。
问题背景
在v5中,我们可以通过<Route>组件直接使用params属性获取路由参数,代码如下:
// v5写法
<Route path="/user/:id" component={UserComponent} />
// 在组件中访问参数
function UserComponent({ match }) {
const userId = match.params.id;
// 处理逻辑
}
但在v6中,match属性被移除,参数获取方式完全改变。
踩坑过程
升级后发现所有依赖参数传递的页面都报错。经过排查,主要问题在于:
useParams()Hook是v6新引入的API- 之前通过
match.params获取的参数,现在必须使用useParams() - 路由嵌套时参数传递更加复杂
解决方案
以下是几种常用的解决方案:
方案一:使用useParams Hook
import { useParams } from 'react-router-dom';
function UserComponent() {
const { id } = useParams();
// 使用id参数
}
方案二:处理嵌套路由参数
// 路由配置
<Routes>
<Route path="/user/:userId" element={<UserLayout />}>
<Route path="profile" element={<UserProfile />} />
<Route path="settings" element={<UserSettings />} />
</Route>
</Routes>
// 在子组件中获取父级参数
function UserProfile() {
const { userId } = useParams(); // 可以获取到userId
}
方案三:传递额外参数
// v6中推荐使用state传递
<Link to={{
pathname: `/user/${id}`,
state: { from: 'dashboard' }
}}>
// 在目标组件中获取
const location = useLocation();
const from = location.state?.from;
注意事项
- 所有使用参数的地方都要替换为
useParams() - 之前的
withRouter高阶组件在v6中已废弃 - 路由配置需要从
<Switch>改为<Routes> history.push等方法需要使用useNavigate替代
升级过程中确实花费了不少时间,但熟悉了新API后发现v6的路由系统更加清晰和灵活。

讨论