在React中处理浏览器的返回按钮

3
在登录我的仪表板组件后,我不希望用户使用浏览器的返回按钮返回到我的登录页面。
我没有使用Redux,只是用React。

可能是如何使用JavaScript停止浏览器返回按钮的重复问题。 - undefined
如果用户已经登录,为什么不将用户重定向到“仪表板”组件而不是在“登录”组件中呢? - undefined
1
当用户点击返回按钮时,预期的行为是什么? - undefined
将其重定向到同一页面。 - undefined
2个回答

4
我认为这会有所帮助,如果用户已登录,则停留在当前页面。
if(loggedIn) {
  history.pushState(null, null, location.href);
  window.onpopstate = function(event) {
  history.go(1);
  };
}

1
componentDidMount() { const { loggedIn } = this.state; const { history, location } = window; if (loggedIn) { history.pushState(null, null, location.href); window.onpopstate = event => { event.preventDefault(); history.go(1); }; } }componentDidMount() { const { loggedIn } = this.state; const { history, location } = window; if (loggedIn) { history.pushState(null, null, location.href); window.onpopstate = event => { event.preventDefault(); history.go(1); }; } } - undefined
对我来说,它回到以前然后返回到当前页面。 - undefined

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]);
}

现在我可以在我的组件中调用useNavigateBack([自定义的返回导航处理程序])。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接