【问题标题】:Is there a function, like componentWillUnmount, that will fire before the page is refreshed是否有一个函数,比如 componentWillUnmount,会在页面刷新之前触发
【发布时间】:2020-11-23 10:25:34
【问题描述】:

我想要一个函数,在用户刷新页面之前向服务器发送请求(不关心响应)。

我尝试过使用componentWillUnmount 方法,但页面刷新没有调用此函数。例如

import React, { useEffect } from 'react';

const ComponentExample => () => {
    useEffect(() => {
        return () => {
            // componentWillUnmount in functional component.
            // Anything in here is fired on component unmount.
            // Call my server to do some work
        }
    }, []) }

有人知道怎么做吗?

【问题讨论】:

  • componentDidMount() 是您应该使用的函数。
  • 检查 this 本地事件的答案
  • componentDidMount() 将在组件加载时触发。我希望在页面即将刷新时触发一个函数。
  • 感谢@kunquan,但该本地事件提供了一个确认对话框。我想要一个函数,所以我可以在页面刷新之前做一些工作
  • 您可以在该函数中做一些工作。对话框只是默认行为。

标签: javascript reactjs


【解决方案1】:

您可以尝试监听window.beforeunload 事件。

beforeunload 事件在窗口、文档及其 资源即将被卸载。该文档仍然可见并且 此时活动仍可取消。

useEffect(() => {
  const unloadCallback = (event) => { ... };

  window.addEventListener("beforeunload", unloadCallback);
  return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);

注意:这将响应导致页面卸载的任何事情

注2:

但请注意,并非所有浏览器都支持此方法,有些浏览器 而是要求事件处理程序实现两个遗留的之一 方法:

  • 将字符串分配给事件的 returnValue 属性
  • 从事件处理程序返回一个字符串。

【讨论】:

  • 完美。这就是我一直在寻找的。对于看到这里的任何人,我必须在回叫中添加一行:unloadCallBack = e => { // do work delete e['returnValue'] }
  • 建议您使用beforeunload 而不是unload
  • @Joshua 谢谢。在我的测试中,我没有注意到两者之间的区别,但在阅读官方文档后我同意。
【解决方案2】:

您几乎可以通过检查页面是否已刷新来做到这一点。

来源:https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API

例子:

if (window.performance) {
  console.info("window.performance is supported");
  console.info(performance.navigation.type);

  if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
    console.info( "This page is reloaded" );
  } else {
    console.info( "This page is not reloaded");
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    相关资源
    最近更新 更多