是否有一个函数,例如componentWillUnmount,将在刷新页面之前触发 [英] Is there a function, like componentWillUnmount, that will fire before the page is refreshed

查看:76
本文介绍了是否有一个函数,例如componentWillUnmount,将在刷新页面之前触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want a function, to send a request to a server (don't care about response) before a user refreshes the page.

我尝试使用 componentWillUnmount 方法,但是页面刷新未调用此函数.例如

I've tried using the componentWillUnmount approach but the page refresh doesn't call this function. e.g.

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
        }
    }, []) }

有人知道如何做到这一点吗?

Does anyone have any ideas how to do this?

推荐答案

您可以尝试收听

在窗口,文档及其窗口中触发 beforeunload 事件资源即将被卸载.该文档仍然可见,并且该事件目前仍可取消.

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

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

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

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

Note: This will respond to anything that causes the page to unload though.

注意2:

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

However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:

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

这篇关于是否有一个函数,例如componentWillUnmount,将在刷新页面之前触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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