React-router, onEnter 导致带有身份验证的无限循环 [英] React-router, onEnter cause infinite loop with authentication

查看:47
本文介绍了React-router, onEnter 导致带有身份验证的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按照这个例子:

https://github.com/ReactTraining/react-router/blob/v3/examples/auth-flow/app.js

我想阻止用户在 loggedIn 后导航 login 路由器.

I want to prevent users to navigate login router after they are loggedIn.

我尝试将 requireAuth 放到 login 路由器的 onEnter 中.

I tried to put the requireAuth to the onEnter of login router.

但是,当用户第一次访问页面时,他们没有loggedIn,会导致无限循环.

But, when a user access the page for the first time, they are not loggedIn, and it will cause infinite loop.

在我的情况下如何跳出循环?这是我的代码:

How can I get out of loop in my case? here is my code:

{
  path: 'login',
  component: Login,
  onEnter: (nextState, replace) => {
    if(!auth.loggined) {
      replace({
        pathname: '/login',
        state: {
          nextPathname: nextState.location.pathname
        }
      })
    } else {
      replace('/')
    }
  }
}

推荐答案

为什么要尝试将 requireAuth 添加到 login 页面?

Why are you trying add requireAuth to the login page?

我相信你的onEnter应该是这样的

I believe your onEnter should be like this

if(loggedIn){
    replace({
      pathname: '/'
    })
}

仅此而已,如果您想阻止经过身份验证的用户访问此页面.

and nothing more, if you want to prevent access to this page for authenticated users.

这篇关于React-router, onEnter 导致带有身份验证的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆