React Router跳转错误页后点击浏览器回退按钮无法返回应用前页面怎么办
实现方案
问题核心是当前跳转错误页时使用了push方式新增历史记录,导致/gg路径仍残留在历史栈中,回退时就会回到该页面,修改跳转方式即可解决:
1 调整错误页跳转逻辑(首选方案)
将原有的history.push跳转改为replace模式,直接用错误页的历史记录覆盖当前的/gg记录,历史栈中就不会留存/gg的访问痕迹,回退时会直接跳到进入应用前的页面。
React Router v5 写法
// 函数组件 import { useHistory } from 'react-router-dom' // axios请求失败的回调中 const history = useHistory() // 可根据当前路径前缀匹配对应的错误页路径 const errorPath = location.pathname.startsWith('/gg') ? '/gg/error' : '/error' history.replace(errorPath)
// 类组件配合withRouter高阶组件 import { withRouter } from 'react-router-dom' // 请求失败回调中 const errorPath = this.props.location.pathname.startsWith('/gg') ? '/gg/error' : '/error' this.props.history.replace(errorPath)
React Router v6 写法
import { useNavigate } from 'react-router-dom' const navigate = useNavigate() const errorPath = location.pathname.startsWith('/gg') ? '/gg/error' : '/error' navigate(errorPath, { replace: true })
2 错误页兜底处理(可选)
如果跳转逻辑不方便修改,可以在Error组件中监听回退事件,手动跳过/gg的历史记录:
import { useEffect } from 'react' const Error = () => { useEffect(() => { const handlePopstate = () => { // 确认前一条记录是/gg路径时,直接回退两步 if (window.history.length >= 2) { window.history.go(-2) } } window.addEventListener('popstate', handlePopstate) return () => window.removeEventListener('popstate', handlePopstate) }, []) // 原有Error组件的渲染逻辑 return <div>错误页内容</div> }
注:该方案需要做好边界判断,避免用户直接访问错误页时多跳层级
内容的提问来源于stack exchange,提问作者Javid Isayev
相关产品推荐
相关产品推荐

