【问题标题】:onbeforeunload not working inside react componentonbeforeunload 在反应组件内不起作用
【发布时间】:2019-02-26 04:04:04
【问题描述】:

我有一个简单的反应组件,用户可以在其中编辑数据。由于可能更改的值可能需要一些时间,因此我想请用户在离开页面时确认以防更改未保存。

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

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"

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

【问题讨论】:

  • 这可能是一个不费吹灰之力的假问题,很抱歉问,但只是为了确定:您是否设置了 returnValue/prevent default before return线? (例如,您不会在实际发生之前提前返回)
  • 我尝试在函数的最后返回null'' 以及字符串Do something - 没有发生任何事情。我知道不会显示/不支持自定义字符串或警报。但至少对话(随处可见)会很高兴......
  • 所以我想知道你是否绑定在 mount 上而不是它会起作用。但至于为什么当它不在构造函数中时它会起作用,我不确定!
  • 啊,刚刚也有人回答了这个问题 :)

标签: javascript reactjs typescript


【解决方案1】:

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

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

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

【讨论】:

  • 确实,这是有效的(同时使用 Chrome 修复程序时)​​。知道为什么它只在绑定componendDidMount 时才有效吗?至少在构造函数中绑定时,我的断点受到了影响(这意味着某些内容已被绑定)。
  • 在 react 中,如果你需要处理 React 尚未提供的 DOM 事件,你必须在组件挂载后添加 DOM 监听器
  • 要使用钩子实现这些,请参阅stackoverflow.com/questions/53464595/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 2021-03-13
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 2021-06-27
  • 2018-08-31
相关资源
最近更新 更多