REACT - 在渲染 APP 之前检查身份验证 [英] REACT - Check authentication before render APP

查看:42
本文介绍了REACT - 在渲染 APP 之前检查身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的被困在这里,我不知道为什么,我对 React 有点陌生,所以我能得到的每一个帮助都会被认为是很棒的 :D!

Im really stuck here and im not sure why, im kind of new to React so every help i can get would be consider great :D!

当用户登录时,我在 localstorage 中存储了一个 JWT 令牌,当我们刷新页面时,我有这个功能来检查用户是否通过身份验证,以便我们可以再次设置用户.

I have stored a JWT token inside localstorage when USER is signed in, when we refresh the page i have this function to check if the user is authenticated so we can set the user again.

async checkLoginStatus() {
    console.log('checking');
    const token = localStorage.getItem('sid');
    if (token) {
      let user = await VerifyUser(token);
      if (user) {
        this.setState({
          isLoggedin: true,
          user: user
        });
      } else {
        this.setState({
          isLoggedin: false,
          user: {}
        });
      }
    } else {
      this.setState({
        isLoggedin: false,
        user: {}
      });
    }
  }

  componentDidMount() {
    this.checkLoginStatus();
  }

这是我的路线自动取款机,不要介意代码的差异,测试一些东西

Here is my routes atm, dont mind the diff of the codes, testing some stuff

<Router>
            <Header handleLogin={this.handleLogin} isLoggedin={this.state.isLoggedin} handleLogout={this.handleLogout} />
            <Switch>
              <Route exact path="/about" component={About} />
              <Route exact path="/portfolio" component={Portfolio} />
              <Route exact path="/" component={ () => <Home user={this.state.user}/> } />
              <PrivateRoute exact path="/user" isLoggedIn={this.state.isLoggedin} component={User} />
            </Switch>
        </Router>

这是我的私人路线

const PrivateRoute = ({ component: Comp, isLoggedIn, path, ...rest }) => {
    return (
      <Route path={path} {...rest} render={props => {
          return isLoggedIn ? (<Comp {...props} />) : (<Redirect to="/" />);
        }}
      />
    );
  };

export default PrivateRoute;

当用户登录时,他们可以访问受保护的页面,但当他们退出时,他们不能访问.所以这很好用.当我刷新站点上任何地方的页面时,它会检查我们是否有令牌并登录用户,这也不是问题.

When the user is logged in they can access the Protected page, but when they are logged out they cannot. So that works fine. And when i refresh page anywhere on the site, it checks if we have a token and it login the user, this is not the problem aswell.

问题是当我站在/user <- 受保护的页面上,然后刷新页面时,用户未登录,我猜是因为我们检查要登录的用户的功能尚未完成然而,当我们尝试渲染该路线时.我试过将 componentDidMount 更改为 componentWillMount 没有结果.

The problem is when i am standing on /user <- the protected page, and i refresh page, the user is not logged in, i guess because the function where we check the user to be logged in has not been done yet when we try to render that route. Ive tried changing componentDidMount to componentWillMount with no results.

有什么建议吗?

推荐答案

问题是isLoggedIn的初始值为falsey,触发重定向(状态异步更新之前):

The problem is that initial value of isLoggedIn is falsey, which triggers the redirect (before the state is updated asynchronously):

isLoggedIn ? (<Comp {...props} />) : (<Redirect to="/" />)

您需要的是加载"、登录成功"和登录失败"的 3 个状态.

What you need is 3 states for 'loading', 'login succes' and 'login fail'.

具有 2 个布尔变量的示例:

Example with 2 boolean variables:

state = {
  isLoading: true,
  isLoggedIn: false,
  user: {}
}
...
    this.setState({
      isLoading: false,
      isLoggedIn: false
    })
...
    isLoggedIn ? (<Comp {...props} />) : (isLoading ? 'Loading...' : <Redirect to="/" />)

(如果你喜欢更少的变量,同样可以用初始状态 isLoggedIn: null 和条件 isLoggedIn === null 来实现)

(the same can be achieved with initial state isLoggedIn: null and condition isLoggedIn === null if you prefer fewer variables)

这篇关于REACT - 在渲染 APP 之前检查身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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