单击“后退”按钮时,我一直试图向用户显示确认弹出窗口。我正在使用React Router v3
,因此我无法使用React Router v4的<Prompt/>
。
以下是我想要实现的目标:
我尝试过几件事:
1)setRouteLeaveHook (React Router v3)React Router v3 doc
componentDidUpdate() {
...
if (isDirty) // denoting that there is unsaved work
this.props.router.setRouteLeaveHook(
this.props.route,
() => { return 'Unsaved data will be lost' }
);
}
withRouter
包装了我的组件,以便我可以访问this.props.router
www.website.com/about
www.website.com
2)'beforeunload'和'popstate'
www.website.com
componentDidUpdate() {
...
if (isDirty) // denoting that there is unsaved work
window.addEventListener('beforeunload', this.handleBeforeUnload);
window.addEventListener('popstate', this.handleOnPopState);
}
}
handleBeforeUnload = e => {
e.preventDefault();
const msg = 'Are you sure?';
e.returnValue = msg;
return msg;
}
handleOnPopState = e => {
e.preventDefault();
// how can I prevent here?
}
时,会弹出确认消息并按原样运行。防止用户意外导航的最佳方法是什么? 任何帮助或建议表示赞赏!!
P.S。我无法升级到React Router v4