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

Rav*_*hra 5 javascript reactjs react-router-v4

我试图仅在 react 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);
   });
}
Run Code Online (Sandbox Code Playgroud)

Her*_*tel 5

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

如果您的组件不是直接路由组件,您可以使用withRouter来自react-router或 的高阶react-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);
     });
   }      
}
Run Code Online (Sandbox Code Playgroud)