useBeforeUnload
這個 Hook 只是 window.beforeunload
的一個輔助工具。
當使用者點擊尚未造訪的頁面連結時,Remix 會載入該頁面的程式碼分割模組。如果您在使用者工作階段中部署,而您或您的主機從伺服器中移除舊檔案(許多主機都會這樣 😭),那麼 Remix 對這些模組的請求將會失敗。Remix 會自動重新載入新網址的瀏覽器來恢復。這應該會從伺服器以應用程式的最新版本重新開始。大多數情況下,這會運作良好,使用者甚至不會知道發生任何事情。
在這種情況下,您可能需要在頁面上儲存重要的應用程式狀態(例如儲存到瀏覽器的本機儲存空間),因為自動頁面重新載入會遺失您擁有的任何狀態。
無論是否使用 Remix,這都是一個好習慣。使用者可以變更網址、意外關閉瀏覽器視窗等。
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 <>{/*... */}</>;
}