javascript - 在 React 中确认“返回”的导航
问题描述
单击“后退按钮”时,我一直在尝试向用户显示确认弹出窗口。我正在使用React Router v3
,所以我不能使用<Prompt/>
React Router v4。
这是我想要实现的目标:
- 当用户在表单上单击“返回”或“刷新”并使用未保存的数据时,浏览器会显示确认弹出窗口“是”和“否”以离开或留下。
我尝试了几件事:
1) setRouteLeaveHook (React Router v3) React Router v3 文档
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
- 弹出消息出现,我单击“否”以留在同一页面上
- 虽然内容(组件)一样,但是url改回
www.website.com
2) 'beforeunload' 和 'popstate'
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?
}
- 在这里,弹出确认消息并按我尝试时应有的方式工作
reload
。 - 但是,当我单击后退按钮时,没有确认也不会阻止“返回”。
防止用户意外导航的最佳方法是什么?任何帮助或建议表示赞赏!
ps 我无法升级到 React Router v4
解决方案
如果有人遇到同样的问题,请参考我的解决方案:
推荐阅读
- rxjs - RXJS 基于另一个订阅结果重试
- mysql - Mysql查询只显示受影响的行而不是表
- python - 在 IIS 下运行 FastAPI
- terraform - 您如何通过 vapp 属性接受 vcsa EULA?
- flutter - 是否支持在 Flutter 中使用 Facebook SDK(具体的应用事件)?
- python - 为什么像这样对数据进行洗牌会导致准确性不佳
- java - 无法启动 quarkus:无法从类 io.quarkus.deployment.logging.LoggingResourceProcessor 加载步骤
- typescript - 我无法为 Pulumi 创建集群,因为代码正在标记,请协助
- logging - 卡夫卡大日志问题 - 真的不知道发生了什么
- python - 行和的 Python 等效项