如何在React 17搭配react-route 6的项目中实现线性路由导航并自定义回退路径
核心原理
问题本质是/orders/products路由在浏览器历史栈中留存了记录,重定向回/orders时默认是新增历史记录而非替换原有记录,因此点击回退会回到该页面。可以通过以下几种方案实现需求:
方案1:跳转进入/orders/products时使用替换模式(最推荐)
从根源避免/orders/products进入历史栈,后续操作不会出现回退到该页的问题:
- Vue Router 写法:
// 从/orders跳转至/orders/products时调用 router.replace('/orders/products') // 组件内写法 this.$router.replace('/orders/products')
- React Router v6 写法:
const navigate = useNavigate() // 跳转时调用 navigate('/orders/products', { replace: true })
- 原生History API写法:
history.replaceState(null, '', '/orders/products')
方案2:添加商品完成后重定向回/orders时使用替换模式
如果不方便修改之前的跳转逻辑,可以在提交商品后的重定向步骤替换历史栈,直接覆盖/orders/products的历史记录:
- Vue Router 写法:
// 商品提交成功后调用 router.replace('/orders')
- React Router v6 写法:
// 商品提交成功后调用 navigate('/orders', { replace: true })
- 原生History API写法:
history.replaceState(null, '', '/orders')
方案3:在/orders页拦截回退事件强制跳转首页
如果以上两种方案都无法落地,可以直接在/orders页监听浏览器回退行为,触发时直接跳转到/:
- Vue Router 示例:
// 页面挂载时注册监听 onMounted(() => { history.pushState(null, '', location.href) window.addEventListener('popstate', () => { router.replace('/') }) }) // 页面卸载时移除监听避免污染全局 onUnmounted(() => { window.removeEventListener('popstate', () => { router.replace('/') }) })
- React Router 示例:
useEffect(() => { history.pushState(null, '', location.href) const handlePopstate = () => { navigate('/', { replace: true }) } window.addEventListener('popstate', handlePopstate) return () => window.removeEventListener('popstate', handlePopstate) }, [navigate])
优先选择方案1或方案2,符合前端路由标准设计逻辑,无额外事件监听开销,对用户操作侵入性最低。
内容的提问来源于stack exchange,提问作者Joandreiy Cordeiro
相关产品推荐
相关产品推荐

