useBeforeUnload

useBeforeUnload

此钩子只是 window.beforeunload 的一个辅助钩子。

¥This hook is just a helper around window.beforeunload.

当用户点击尚未访问的页面的链接时,Remix 会加载该页面的代码拆分模块。如果你在用户会话期间部署,并且你或你的主机从服务器中删除了旧文件(许多人都会这样做😭),那么 Remix 对这些模块的请求将会失败。Remix 通过在新的 URL 上自动重新加载浏览器来恢复。这将从服务器重新启动,并使用你应用的最新版本。大多数情况下,这样做效果很好,用户甚至不知道发生了什么。

¥When users click links to pages they haven't visited yet, Remix loads the code-split modules for that page. If you deploy in the middle of a user's session, and you or your host removes the old files from the server (many do 😭), then Remix's requests for those modules will fail. Remix recovers by automatically reloading the browser at the new URL. This should start over from the server with the latest version of your application. Most of the time this works out great, and the user doesn't even know anything happened.

在这种情况下,你可能需要将重要的应用状态保存在页面上(例如保存到浏览器的本地存储中),因为自动页面重新加载会丢失你之前的所有状态。

¥In this situation, you may need to save important application state on the page (to something like the browser's local storage), because the automatic page reload will lose any state you had.

无论是否支持 Remix,这都是一个很好的做法。用户可以更改 URL、意外关闭浏览器窗口等。

¥Remix or not, this is a good practice. The user can change the url, accidentally close the browser window, etc.

import { useBeforeUnload } from "@remix-run/react";

function SomeForm() {
  const [state, setState] = React.useState(null);

  // save it off before the automatic page reload
  useBeforeUnload(
    React.useCallback(() => {
      localStorage.stuff = state;
    }, [state])
  );

  // read it in when they return
  React.useEffect(() => {
    if (state === null && localStorage.stuff != null) {
      setState(localStorage.stuff);
    }
  }, [state]);

  return <>{/*... */}</>;
}
Remix v2.17 中文网 - 粤ICP备13048890号