useBeforeUnload
此 Hook 只是 window.onbeforeunload
的一個輔助函式。在使用者導航離開頁面前,在頁面上(例如瀏覽器的本機儲存空間)保存重要的應用程式狀態可能會很有用。這樣,如果使用者返回,你可以還原任何有狀態的資訊(還原表單輸入值等等)。
import { useBeforeUnload } from "react-router-dom";
function SomeForm() {
const [state, setState] = React.useState(null);
// save it off before users navigate away
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 <>{/*... */}</>;
}