v6版本升级后路由跳转验证问题排查记录
问题现象
在将React Router从v5升级到v6后,发现部分路由跳转功能异常,特别是在使用useNavigate hook进行程序化导航时,页面无法正确跳转,且控制台无明显错误信息。
复现步骤
- 创建一个基础的路由组件结构:
const App = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</BrowserRouter>
);
};
- 在组件中使用navigate进行跳转:
const Home = () => {
const navigate = useNavigate();
const handleGoProfile = () => {
navigate('/profile'); // 此处跳转失效
};
return (
<button onClick={handleGoProfile}>跳转到个人页</button>
);
};
- 检查浏览器控制台,发现没有报错信息,但页面未发生跳转。
排查过程
- 检查路由配置:确认
BrowserRouter包裹了整个应用,并且路由路径正确。 - 验证navigate使用:确认在正确的React组件中使用
useNavigatehook。 - 查看v6文档:发现v6版本中,
useNavigate返回的函数签名和行为有所变化,需要确保传参正确。
解决方案
最终定位到问题在于:
- 确保所有路由组件都包裹在
BrowserRouter内 - 使用
useNavigate()时确保组件是React Router上下文中的子组件 - 路由跳转时避免使用相对路径导致的问题,应使用绝对路径
const Home = () => {
const navigate = useNavigate();
const handleGoProfile = () => {
// 确保使用绝对路径
navigate('/profile');
// 或者使用相对路径但需注意上下文
// navigate('../profile');
};
return (
<button onClick={handleGoProfile}>跳转到个人页</button>
);
};
通过以上调整,路由跳转功能恢复正常。

讨论