我试图仅在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);
});
}
最佳答案
如果您使用的是react-router
或react-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);
});
}
}