javascript - onbeforeunload 在反应组件中不起作用
问题描述
我有一个简单的反应组件,用户可以在其中编辑数据。由于可能更改的值可能需要一些时间,因此我想要求用户在离开页面时进行确认,以防更改未保存。
在组件的构造函数中,我调用:
window.addEventListener("beforeunload", this.handleWindowBeforeUnload);
我也试过
window.onbeforeunload = this.handleWindowBeforeUnload;
handleWindowBeforeUnload
看起来像这样:
private handleWindowBeforeUnload = (ev: BeforeUnloadEvent): string => {
return "Unsaved changes. Are you sure?";
}
但是,设置断点会命中。但尽管如此,没有任何迹象表明离开可能是危险的。也尝试使用最新的 Firefox,但没有任何反应。如MDN所述,我也尝试过
// Cancel the event as stated by the standard.
e.preventDefault();
// Chrome requires returnValue to be set.
e.returnValue = '';
// return something to trigger a dialog
return null; // ''; // "Do something"
仍然没有任何反应。我在这里做错了什么?
解决方案
您需要在生命周期方法中调用该方法:
componentDidMount() {
window.addEventListener("beforeunload", this.handleWindowBeforeUnload);
}
componentWillUnmount() {
window.removeEventListener("beforeunload", this.handleWindowBeforeUnload);
}
推荐阅读
- python - Python - 如何通过 openpyxl 或其他模块读取 excel 中的计算公式?
- c# - 如何编写一个返回 xaml 切换开关的值的方法?
- html - Flexbox 没有按预期流动
- c++ - 循环通过自定义列表中的项目后 C++ 崩溃
- elasticsearch - 使用 Spring Data ElasticSearch 从 elasticsearch DB 获取索引数据
- java - 为什么我的代码在我引用它之前就进行了评估
- r - 日期事件变量前 R 天
- google-sheets - REGEXMATCH - 多个关键词
- python - Python - Opencv 读取 qr 图像
- javascript - 将 crypto.js 与 openssl 一起使用