I am having the below problems when handling the back button in React:
- The first popstate event is not being called at the first time
- It is called twice after executing my back button custom logic
To solve problem 1, I did the following code:
componentDidMount() {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', this.onBackButtonEvent);
}
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;
}
}
}
Don't forget to add this.isBackButtonClicked = false; in the constructor and unscubscribe the events.
componentWillUnmount = () => {
window.removeEventListener('popstate', this.onBackButtonEvent);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…