react-router-dom触发返回事件时如何让history回退两次跳过指定路由
路由返回拦截实现方案(C3跳转C1跳过C2)
核心逻辑是在C3组件挂载时向浏览器历史栈插入当前路由的占位记录,拦截返回事件后直接替换路由到/c1,避免遗留多余历史记录影响后续操作。
- 注意:如果存在从C3跳转到其他非C1页面的需求,跳转前必须先移除
popstate事件监听,否则会导致其他页面的返回逻辑异常
1. Vue Router 实现
在C3组件的生命周期钩子中添加监听逻辑即可:
<script setup> import { useRouter, onMounted, onUnmounted } from 'vue-router' const router = useRouter() const interceptBack = (e) => { e.preventDefault() // 用replace替换历史栈,避免C1页面返回还能回到C3 router.replace('/c1') } onMounted(() => { // 插入占位历史记录,触发返回时不会直接跳转到C2 window.history.pushState(null, null, window.location.href) window.addEventListener('popstate', interceptBack) }) onUnmounted(() => { window.removeEventListener('popstate', interceptBack) }) </script>
2. React Router v6 实现
用useEffect配合useNavigate实现:
import { useEffect } from 'react' import { useNavigate } from 'react-router-dom' const C3 = () => { const navigate = useNavigate() const interceptBack = (e) => { e.preventDefault() navigate('/c1', { replace: true }) } useEffect(() => { window.history.pushState(null, null, window.location.href) window.addEventListener('popstate', interceptBack) // 组件卸载时清除监听 return () => window.removeEventListener('popstate', interceptBack) }, [navigate]) return <div>C3组件内容</div> } export default C3
3. 原生JS实现
无框架场景下直接操作history API:
// C3页面加载完成后执行 window.addEventListener('load', () => { window.history.pushState(null, null, window.location.href) }) window.addEventListener('popstate', (e) => { e.preventDefault() location.replace('/c1') })
内容的提问来源于stack exchange,提问作者Constantin
相关产品推荐
相关产品推荐

