onbeforeunload在React组件内部不起作用 [英] onbeforeunload not working inside react component

查看:100
本文介绍了onbeforeunload在React组件内部不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的react-component,用户可以在其中编辑数据.由于可能会更改的值可能需要一些时间,因此我想请用户在离开页面时进行确认,以防未保存更改.

I have a simple react-component where a user can edit data. As the values that may be changed could take some time I want to ask the user to confirm when leaving the page in case of unsaved changes.

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

In the component's constructor I call:

window.addEventListener("beforeunload", this.handleWindowBeforeUnload);

我也尝试过

window.onbeforeunload = this.handleWindowBeforeUnload;

handleWindowBeforeUnload 看起来像这样:

private handleWindowBeforeUnload = (ev: BeforeUnloadEvent): string => {
    return "Unsaved changes. Are you sure?";
}

但是,设置断点会命中.但是,没有任何迹象表明离开可能是危险的.还尝试使用最新的Firefox,但没有任何反应.正如MDN所述,我也尝试过

However, setting a breakpoint will hit. But nevertheless there is no prompt showing that leaving may be dangerous. Also tried with latest Firefox but nothing happened. As stated on MDN I also tried

// 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"

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

Still nothing happens. What am I doing wrong here?

推荐答案

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

You'll need to call the method inside the lifecycle methods:

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

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

这篇关于onbeforeunload在React组件内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆