Javascript 有没有像componentWillUnmount这样的函数会在刷新页面之前触发

Javascript 有没有像componentWillUnmount这样的函数会在刷新页面之前触发,javascript,reactjs,Javascript,Reactjs,我想要一个函数,在用户刷新页面之前向服务器发送请求(不关心响应) 我尝试过使用组件willunmount方法,但是页面刷新没有调用此函数。e、 g import React, { useEffect } from 'react'; const ComponentExample => () => { useEffect(() => { return () => { // componentWillUnmount in fun

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

我尝试过使用
组件willunmount
方法,但是页面刷新没有调用此函数。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
        }
    }, []) }

有人知道怎么做吗?

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

资料来源:

例如:

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

你可以试着听听这个事件

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

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

注2:

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

  • 将字符串指定给事件的returnValue属性
  • 从事件处理程序返回字符串

componentDidMount()是您应该使用的函数。检查本机事件的答案
componentDidMount()
将在组件加载时触发。我想在页面即将刷新时启动一个函数。谢谢@kunquan,但该本地事件会提供一个确认对话框。我想要一个函数,所以我可以在页面刷新之前做一些工作。您可以在该函数内部做一些工作。对话框只是默认的行为。完美。这就是我要找的。对于在这里查看的任何人,我必须在回拨中添加一行:
unload callback=e=>{//do work delete e['returnValue']}
建议您在卸载前使用
而不是
unload
@Joshua谢谢。在我的测试中,我没有注意到两者之间的区别,但在阅读官方文件后,我同意。
useEffect(() => {
  const unloadCallback = (event) => { ... };

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