English 中文(简体)
在用户离开你的网页时,如何发送有关终点的数据?
原标题:How to send a data on end point, when user leave your page?

在用户离开我的网页或浏览器时,我需要发送一些数据。 哪些事件应当使用? 我正在使用反应堆和轴心,或许可以采取某种办法。

我试图使用卸载、卸载和上载,但定期工作。 有时它发送数据,但当我试图再次这样做时,它就没有工作。 而且,我不需要一个登峰/标签表格,该表要求用户确认填写表格,以显示该页即将关闭。

问题回答

我认为,当用户离开你的网页或关闭浏览器时,你想要发送数据时,<代码>在<<>unload>之前即为一种常用的方法。

Using beforeunload event can trigger a confirmation dialog in some browsers, and there s no guaranteed time for the network request to complete.

One alternative is to use the unload event, which is fired just before the page is unloaded. Keep in mind that, similar to beforeunload, the unload event is also limited in terms of reliability for sending data.

添加使用<代码>unload的样本代码:

import React, { useEffect } from  react ;
import axios from  axios ;

const MyComponent = () => {
  useEffect(() => {
    const cleanup = async () => {
      try {
        await axios.post( your-api-endpoint , { yourData });
      } catch (error) {
        console.error( Error sending data on unload: , error);
      }
    };

    window.addEventListener( unload , cleanup);

    return () => {
      cleanup();
      window.removeEventListener( unload , cleanup);
    };
  }, []);

  return (
    <div>
      {/* Your component content */}
    </div>
  );
};

export default MyComponent;




相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签