使用react-router-dom v6进行页面导航时处理浏览器的beforeunload事件。

huangapple go评论56阅读模式
英文:

Handle Browser beforeunload with react-router-dom v6 page navigation

问题

我有一个使用react-router v6构建的简单应用程序,我的用例是在页面卸载时使用最后更新的状态调用API。

const handleBeforeUnload = () => {
  console.log("Running unload");
};

React.useEffect(() => {
  window.addEventListener("beforeunload", handleBeforeUnload);
  return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, []);

在上述代码中,当我重新加载浏览器时,处理程序被调用。但是,当我尝试通过具有NavLink的侧边栏导航时,卸载不会被调用,因为react-router-dom执行客户端端路由,因此页面实际上从未被卸载。那么,如何在react-router-dom导航时在页面卸载时运行这段代码?

示例代码:https://codesandbox.io/s/lingering-pond-gt5u6d

英文:

I have a simple application with the navigation built with react-router v6. My use case is to call an API with the last updated state on page unload.

const handleBeforeUnload = () => {
  console.log("Running unload");
};

React.useEffect(() => {
  window.addEventListener("beforeunload", handleBeforeUnload);
  return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, []);

With the above code when I reload the browser the handler is getting called. But when I'm trying to navigate via sidebar having NavLink, the unload is not getting called because react-router-dom do client side routing so page is not actually never getting unload. So How can I run the piece of code on page unload with react-router-dom Navigation?

Sample Code:- https://codesandbox.io/s/lingering-pond-gt5u6d

答案1

得分: 0

以下是已翻译的内容:

You'll need to handle all the different ways a user leaves the component differently. Use beforeunload when the page is reloaded or closed, use an effect cleanup function to handle when the component is just unmounted.

Example:

React.useEffect(() => {
  const handleBeforeUnload = () => {
    console.log("Running unload");
  };

  // handles when page is unloaded
  window.addEventListener("beforeunload", handleBeforeUnload);

  // cleanup function handles when component unmounts
  return () => {
    window.removeEventListener("beforeunload", handleBeforeUnload);

    handleBeforeUnload();
  };
}, []);
英文:

You'll need to handle all the different ways a user leaves the component differently. Use beforeunload when the page is reloaded or closed, use an effect cleanup function to handle when the component is just unmounted.

Example:

React.useEffect(() => {
  const handleBeforeUnload = () => {
    console.log("Running unload");
  };

  // handles when page is unloaded
  window.addEventListener("beforeunload", handleBeforeUnload);

  // cleanup function handles when component unmounts
  return () => {
    window.removeEventListener("beforeunload", handleBeforeUnload);

    handleBeforeUnload();
  };
}, []);

huangapple
  • 本文由 发表于 2023年2月24日 05:18:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定