admin管理员组文章数量:1399981
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.
本文标签: javascriptHandling Back Button from browser in ReactStack Overflow
版权声明:本文标题:javascript - Handling Back Button from browser in React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744168613a2593670.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论