【发布时间】:2019-06-20 05:33:28
【问题描述】:
当我点击浏览器的后退按钮然后点击确认框中的“取消”按钮时,我无法阻止路径重定向。
componentDidMount() {
window.addEventListener('popstate', this.quit);
}
quit = () => {
if(confirm('Quit?')) {
location.assign('/'); // Refreshes the browser then redirects to the homepage
history.pushState(null, null, null); // Clears the previous history
} else {
// What to do if the user clicks "Cancel"?
}
}
我尝试了return false,但它仍在将应用程序重定向到主页(但没有刷新页面)。我尝试过其他解决方案,例如 location.pathname = '/currentPathname' 和 location.replace('/currentPathname'),但由于这些解决方案重新加载浏览器,它会显示 Cannot get /currentPathname,因为 React Router 不需要重新加载。 <Prompt /> 组件也没有解决问题,因为它没有我可以执行上面代码的函数道具。
【问题讨论】:
-
尝试将事件监听器改为
beforeunload而不是popstate -
更糟。没有确认和刷新页面
-
试试这个页面上的建议:stackoverflow.com/questions/32841757/…
-
实现初始目标的最佳选择是使用
<Prompt />来防止不必要的导航。我不确定你为什么需要执行那段特定的代码,因为浏览器通常会处理这个问题。我还尝试创建了一个 CodeSandbox:codesandbox.io/s/m3o0wv1w29 -
问题解决了!
<Prompt />在componentDidMount和componentWillUnmount的帮助下解决了这个问题。谢谢大家!
标签: reactjs react-router browser-history