小编典典

onbeforeunload在React组件内部不起作用

reactjs

我有一个简单的react-
component,用户可以在其中编辑数据。由于可能更改的值可能会花费一些时间,因此我想请用户确认是否在未保存更改的情况下离开页面。

在组件的构造函数中,我调用:

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"

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


阅读 1444

收藏
2020-07-22

共1个答案

小编典典

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

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

componentWillUnmount() {
  window.removeEventListener("beforeunload", this.handleWindowBeforeUnload);
}
2020-07-22