React中针对特定页面禁用浏览器返回按钮

6
我正在尝试在React Redux项目中仅针对特定页面阻止浏览器后退按钮。 假设我有四个页面,用户可以在其中所有页面间来回切换,除了“page4”。一旦用户访问了“page3”并点击了下一步按钮,他就无法返回。我尝试了多种选项,但没有一个如预期的工作。以下代码符合我的预期,但会阻止所有页面的浏览器后退。
componentDidMount() {
   window.history.pushState(null, document.title, window.location.href);
   window.addEventListener('popstate', function (event){
       window.history.pushState(null, document.title,  window.location.href);
   });
}
2个回答

5
如果您正在使用react-routerreact-router-dom,则可以根据当前路由路径有条件地禁用浏览器的后退按钮。
如果您的组件不是直接路由组件,则可以使用react-routerreact-router-dom中的withRouter高阶组件。
componentDidMount() {
   const { match } = this.props;
   if(match.url === "/abc/#/page4"){
     window.history.pushState(null, document.title, window.location.href);
     window.addEventListener('popstate', function (event){
        window.history.pushState(null, document.title,  window.location.href);
     });
   }      
}

1
我已经尝试过这个方法。这样做会导致你无法注册监听器,因为componentDidMount只会执行一次。 - Ravi Kant Mishra

2
您可以使用 react-router-dom 来实现此功能。
import { useHistory } from "react-router-dom";

let history = useHistory();
history.replace("/login");

如果您想在注销函数中执行此操作:
const logoutClicked = () => {
    localStorage.clear(); //if you want to clear localstorage data
    history.replace("/login"); //redirect to login
  };

如果使用的是react-router-dom 6及以上版本,请使用useNavigate而不是useHistory:

import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
navigate("/login");

对于react-router-dom的较新版本,您需要使用useNavigate而不是useHistory。请参见此处:https://bobbyhadz.com/blog/react-export-usehistory-was-not-found-in-react-router-dom#:~:text=To%20solve%20the%20error%20%22export,that%20lets%20you%20navigate%20programmatically. - theQuestionMan

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