使用 React 的浏览器后退按钮 [英] Browser back button using React
问题描述
我正在使用 React.我想在用户点击后退按钮时警告用户.
I am using React. I want to warn the user when the user clicks on the back button.
我所做的是
handleWindowClose = (ev) => {
ev.preventDefault();
return ev.returnValue = 'Leaving this page will loose data';
}
componentDidMount = () => {
window.addEventListener('beforeunload',this.handleWindowClose);
}
componentWillUnmount = () => {
window.removeEventListener('beforeunload',this.handleWindowClose);
}
但是,这不适用于单击后退按钮.所以我尝试这样做:
However, this does not work with a back button click. So I tried doing this:
handleWindowClose = (ev) => {
ev.preventDefault();
return ev.returnValue = 'Leaving this page will loose data';
}
onBackButtonEvent = (e) => {
e.preventDefault();
if (confirm("Do you want to loose this data")) {
window.history.go(0);
}
else {
window.history.forward();
}
}
componentDidMount = () => {
window.addEventListener('beforeunload',this.handleWindowClose);
window.addEventListener('popstate',this.onBackButtonEvent);
}
componentWillUnmount = () => {
window.removeEventListener('beforeunload',this.handleWindowClose);
window.removeEventListener('popstate',this.onBackButtonEvent);
}
我没有使用 react-router.有没有更好的方法只使用 React 来做到这一点?另外我希望窗口停留在那个页面上而不使用 history.forward() 因为我会失去窗口状态.
I am not using react-router. Is there a better way to do this using only React? Also I want the window to stay on that page without using history.forward() as I will lose the window state.
推荐答案
我在 React 中处理后退按钮时遇到以下问题:
I am having the below problems when handling the back button in React:
- 第一次没有调用第一个 popstate 事件
- 在执行我的后退按钮自定义逻辑后调用了两次
为了解决问题1,我做了以下代码:
To solve problem 1, I did the following code:
componentDidMount() {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', this.onBackButtonEvent);
}
为了解决问题 2,我做了以下代码:
To solve problem 2, I did the below code:
onBackButtonEvent = (e) => {
e.preventDefault();
if (!this.isBackButtonClicked) {
if (window.confirm("Do you want to save your changes")) {
this.isBackButtonClicked = true;
// Your custom logic to page transition, like react-router-dom history.push()
}
else {
window.history.pushState(null, null, window.location.pathname);
this.isBackButtonClicked = false;
}
}
}
不要忘记在构造函数中添加 this.isBackButtonClicked = false; 并取消事件.
Don't forget to add this.isBackButtonClicked = false; in the constructor and unscubscribe the events.
componentWillUnmount = () => {
window.removeEventListener('popstate', this.onBackButtonEvent);
}
这篇关于使用 React 的浏览器后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!