[英]Handling Back Button from browser in React
登錄我的儀表板組件后,我不希望用戶使用瀏覽器中的后退按鈕返回我的登錄頁面。
我不使用 Redux,只使用 React。
我認為這會有所幫助,如果用戶已登錄,則留在同一頁面上。
if(loggedIn) {
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
}
我更喜歡使用我的自定義鈎子來攔截瀏覽器的后退導航:
import { useEffect, useRef } from "react"; // Intercepts browser's Navigate Back event export const useNavigateBack = (callback: Function): void => { const isInitialMount = useRef(true); useEffect(() => { if (isInitialMount.current) { isInitialMount.current = false; window.addEventListener('popstate', function(event) { window.history.pushState(null, '', document.URL); event.stopImmediatePropagation(); callback(); }, false); } else { // In my special case this fix was needeed: // window.history.pushState(null, '', document.URL); } }, [callback]); }
現在我可以在我的組件中調用 use useNavigateBack([my custom back navigation handler]) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.