After logging into my Dashboard ponent, I don`t want the user to go back to my login page by using back button in the browser.
I`m not using Redux but only React.
After logging into my Dashboard ponent, I don`t want the user to go back to my login page by using back button in the browser.
I`m not using Redux but only React.
Share Improve this question asked Aug 7, 2017 at 9:44 Prateek ThapaPrateek Thapa 4,9481 gold badge11 silver badges25 bronze badges 4- Possible duplicate of how to stop browser back button using javascript – Liam Commented Aug 7, 2017 at 9:47
-
Why not redirect the user to the
Dashboard
ponent if the user is already logged in, in theLogin
ponent? – glhrmv Commented Aug 7, 2017 at 9:50 - 1 what is expected behaviour when user clicks back button? – Maxim Kuzmin Commented Aug 7, 2017 at 10:03
- Redirecting it to the same page. – Prateek Thapa Commented Aug 7, 2017 at 10:12
2 Answers
Reset to default 4I think this will help, if the user is logged in then stay on the same page.
if(loggedIn) {
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
}
I prefere using my custom hook to intercept browser's back navigation:
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]);
}
And now I can call use useNavigateBack([my custom back navigation handler]) inside my ponent.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744168614a4561424.html
评论列表(0条)