【发布时间】:2023-03-07 06:15:01
【问题描述】:
我正在使用 React。我想在用户点击后退按钮时警告用户。
我所做的是
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);
}
但是,这不适用于单击后退按钮。所以我尝试这样做:
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(),因为我将失去窗口状态。
【问题讨论】:
-
有什么理由不想使用
react-router?
标签: reactjs