1

我正在寻找一种方式,当用户授权时,我存储user authorized status所以我每次都可以检查用户是否是authorized。然而,当我执行下面的代码未授权用户:(Master.jsx - >渲染())存储用户的反应授权

<Route exact path="/" render={() => { 
    console.log('this.props.authed: ', this.props.authed, "this.props: ", this.props) 
    return (
    this.props.authed 
    ? <Home /> 
    : <Redirect from="/" to="/login"/> 
)} 
}/> 

我通过firebasecomponentWillMount()检查用户授权和存储它下面的代码:(Master.jsx - > componentWillMount())

componentWillMount =() => { 

    firebaseAuth().onAuthStateChanged((user) => { 

     if (user) { 
     this.props.login(user) 
     } else { 
     this.props.logout() 
     } 
     }) 
} 

的问题是,将后<Route ..所以用户将被routing后授权componentWillMount将被执行。我有什么办法解决它?

回答

0

这是react-redux的经典用例。我建议所有的认证都在服务器端进行处理,服务器对授权或未授权用户进行真或假响应。在此之前,您可以在用户界面上显示加载图标。

但是,如果您想继续并希望在UI上验证用户身份,请查看react-redux。

从本质上讲,你将有

  1. 在action.js派遣登录动作
  2. 赶上登录动作在你reduce.js和商店要做到这一点

    当用户登录商店中的用户凭证

当用户重新加载/打开页面

  1. 调度在action.js一个isLoggedIn行动
  2. 减少isLoggedIn行动,并检查用户的状态已经存在。如果是,返回允许程序继续。如果否,请求用户再次登录。

希望有所帮助!

+0

如果您看到我的问题,问题是我的存储处理器将在调用react-router后执行。因此,在我将用户数据存储在用户被授权'react-router'重定向到另一页的redux商店之前! –