javascript - 仅在反应中阻止特定页面的浏览器后退按钮
问题描述
我试图仅在 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);
});
}
解决方案
如果您正在使用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);
});
}
}
推荐阅读
- node.js - 如何在 Linux 托管的 NodeJS 上打开 .exe 文件
- angular - 在不使用管道或方法的情况下,如何在 Angular 6 中为 null 时放置 0
- javascript - 赛普拉斯点击/触发未触发 eventListeners
- for-loop - 这个 for 循环的范围是多少?
- powerbi - 由于 X-Frame-Options,PowerBI Embedded 无法正常工作
- python - API 响应错误请求错误消息
- python - 如何标记唯一值?
- php - 如何在 WordPress 帖子上显示多个作者
- python - 如何在 Python 回归模型中合并和预测滞后时间序列变量
- javascript - 我的插件不适用于多个选择器