首页 > 解决方案 > 仅在反应中阻止特定页面的浏览器后退按钮

问题描述

我试图仅在 react redux 项目中阻止特定页面的浏览器后退按钮。假设我有四页。

http://localhost:3000/abc/#/page1,

http://localhost:3000/abc/#/page2,

http://localhost:3000/abc/#/page3

http://localhost:3000/abc/#/page4

ETC

对于所有页面,用户可以来回切换,除了page4. 一旦用户访问page3并单击下一个按钮,他就无法返回。

我尝试了多种选择,但都没有按预期工作。下面的代码按我的预期工作,但它阻止浏览器返回所有页面。

componentDidMount() {
   window.history.pushState(null, document.title, window.location.href);
   window.addEventListener('popstate', function (event){
       window.history.pushState(null, document.title,  window.location.href);
   });
}

标签: javascriptreactjsreact-router-v4

解决方案


如果您正在使用react-routerreact-router-dom则可以根据当前路由路径有条件地禁用浏览器的后退按钮。

如果您的组件不是直接路由组件,您可以使用或的withRouter高阶组件。react-routerreact-router-dom

componentDidMount() {
   const { match } = this.props;
   if(match.url === "/abc/#/page4"){
     window.history.pushState(null, document.title, window.location.href);
     window.addEventListener('popstate', function (event){
        window.history.pushState(null, document.title,  window.location.href);
     });
   }      
}

推荐阅读