在React Router v6升级过程中,我们遇到了一个典型的URL路径拼接问题。当使用useNavigate进行路由跳转时,发现跳转的URL路径异常,例如:从/user/123跳转到/user/123/profile,结果却跳转到了/profile。
复现步骤:
- 在组件中使用
const navigate = useNavigate() - 调用
navigate('/profile')进行相对路径跳转 - 发现跳转后的URL路径拼接错误
问题分析: v6版本的navigate函数在处理相对路径时,会基于当前路由的路径进行拼接。如果当前路径为/user/123,而使用navigate('profile')(注意没有开头斜杠),则会拼接成/user/123/profile;但如果使用navigate('/profile'),则会从根路径开始跳转。
解决方案:
// 错误写法
navigate('/profile'); // 有时会导致路径拼接异常
// 正确写法
navigate('/user/profile'); // 明确指定完整路径
// 或者使用相对路径
navigate('profile'); // 确保当前路径正确
建议在项目中统一使用绝对路径跳转,避免相对路径导致的路径拼接问题。

讨论