首页 > 解决方案 > 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"

仍然没有任何反应。我在这里做错了什么?

标签: javascriptreactjstypescript

解决方案


您需要在生命周期方法中调用该方法:

componentDidMount() {
  window.addEventListener("beforeunload", this.handleWindowBeforeUnload);
}

componentWillUnmount() {
  window.removeEventListener("beforeunload", this.handleWindowBeforeUnload);
}

推荐阅读