是否有一个函数,比如 componentWillUnmount,会在页面刷新之前触发

IT技术 javascript reactjs
2021-04-20 07:32:02

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

我试过使用这种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
        }
    }, []) }

有没有人有任何想法如何做到这一点?

2个回答

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

beforeunload当窗口、文档及其资源即将被卸载时触发事件。文档仍然可见,此时事件仍然可以取消。

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

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

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

笔记2:

但是请注意,并非所有浏览器都支持此方法,有些浏览器需要事件处理程序来实现以下两种遗留方法之一:

  • 为事件的 returnValue 属性分配一个字符串
  • 从事件处理程序返回一个字符串。
建议您使用beforeunload而不是unload
2021-05-24 07:32:02
完美的。这就是我一直在寻找的。对于看这里的任何人,我必须在回调中添加一行:unloadCallBack = e => { // do work delete e['returnValue'] }
2021-05-29 07:32:02
@约书亚谢谢。在我的测试中,我没有注意到两者之间的区别,但是在阅读官方文档时我同意。
2021-06-17 07:32:02

您几乎可以通过检查页面是否已刷新来完成此操作。

来源: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");
  }
}