Javascript 仅在react中防止特定页面的浏览器后退按钮

Javascript 仅在react中防止特定页面的浏览器后退按钮,javascript,reactjs,react-router-v4,Javascript,Reactjs,React Router V4,我试图阻止浏览器返回按钮为特定的网页只在反应redux项目。假设我有四页 http://localhost:3000/abc/#/page1 http://localhost:3000/abc/#/page2 http://localhost:3000/abc/#/page3 和http://localhost:3000/abc/#/page4 等 对于除page4之外的所有页面,用户都可以来回浏览。一旦用户访问了page3并单击了“下一步”按钮,他就无法返回 我尝试了多种选择,但没有一种能像预

我试图阻止浏览器返回按钮为特定的网页只在反应redux项目。假设我有四页

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

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

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

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

对于除
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);
   });
}

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

如果您的组件不是直接路由组件,则可以从
react router
react router dom
使用
with router
高阶组件

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);
     });
   }      
}

我已经试过了。这样,您将无法注册listner,因为componentDidMount将执行一次。