【问题标题】:How to prevent user from going back in react-router-dom?如何防止用户返回 react-router-dom?
【发布时间】:2019-04-05 12:07:33
【问题描述】:

我在我的 reactjs 应用程序中使用 react-router-dom 进行路由。而且我想防止用户在登录后返回,即我不想用户在登录后点击浏览器上的返回按钮时再次返回登录屏幕。

【问题讨论】:

标签: reactjs react-router-dom


【解决方案1】:

使用 React 页面生命周期的componentDidUpdate 方法,您可以在浏览器中处理或禁用返回功能。基本上componentDidUpdate 方法会在组件更新时自动调用。因此,一旦您的组件更新,您可以防止返回如下。

componentDidUpdate() {
  window.history.pushState(null, document.title, window.location.href);
  window.addEventListener('popstate', function(event) {
    window.history.pushState(null, document.title, window.location.href);
  });
}

这将阻止用户返回并使用当前页面作为历史对象的参考。所以即使用户点击浏览器的后退按钮,他们也无法在最后一页返回。

【讨论】:

    【解决方案2】:

    您可以查看此codesandbox 示例,这可能会对您或正在寻找相同内容的人有所帮助。在此我们可以防止用户返回上一页,有关更多详细信息,请查看此medium article。这是一小部分代码

    componentDidMount() {
     const { history } = this.props;
      window.addEventListener("popstate", () => {
      history.go(1);
    });
    }
    

    点击this link.查看完整的工作示例

    【讨论】:

      【解决方案3】:

      你在使用 redux 吗?否则你可以在你的渲染中添加一些东西来检查用户是否已经登录它会将他重定向回他喜欢的页面:

      import { Redirect } from 'react-router'
      
      
      render(){
      //I store my user JWT on this.props.currentUser redux state 
      this.props.currentUser && <Redirect to={'whatever page you want'} /> 
      
      //OR you can also, if you have history, history.goBack()
      
      

      因此,您禁止用户在登录时访问登录页面,而不是禁止返回,而是将他重定向到某个地方或返回到他所在的位置

      【讨论】:

      • 感谢您的建议。不,我还没有在我的应用程序中使用 redux,问题是我的应用程序中没有登录组件,因为我正在使用第三方应用程序进行登录/注册,所以与该应用程序的登录处理相关的所有内容,例如.授权0
      • 哦....我明白了,对不起...
      【解决方案4】:
      window.addEventListener('popstate', function(event) {
      
      });
      

      使用此功能将读取您的浏览器后退按钮单击事件,然后您可以应用任何条件

      【讨论】:

        猜你喜欢
        • 2021-08-21
        • 1970-01-01
        • 2019-03-19
        • 2020-04-24
        • 2022-06-13
        • 1970-01-01
        • 2021-01-24
        • 1970-01-01
        • 2022-07-19
        相关资源
        最近更新 更多