如何维护isAuth和保护私有路由?

How to maintain isAuth and protect private routes?

我正在尝试在 React 中使用 Github oAuth API 实现身份验证,我正在使用 React.CreateContext() 来管理我的 AuthContext。

AuthContext.js

class AuthProvider extends React.Component {
  constructor(props) {
      super(props);
      if(typeof(sessionStorage.getItem('isAuth')) === 'undefined') {
        sessionStorage.setItem('isAuth',false);
      } 
      this.state = { isAuth: sessionStorage.getItem('isAuth') };
      this.login = this.login.bind(this)
      this.logout = this.logout.bind(this)
  }  

  login() {
   this.setState({isAuth: true});
  }

  logout() {
    this.setState({isAuth: false});
  }

当用户点击登录按钮登录方法时,isAuth 设置为 true,用户被重定向到 github 登录页面, 但是一旦用户 returns 访问我的应用程序,组件就会重新初始化并且 isAuth 设置为 false。

我该如何处理?

将状态反映到sessionStorage:

// AuthProvider
componentDidUpdate(prevProps, prevState, snapshot) {
  if(prevState.isAuth !== this.state.isAuth)
    sessionStorage.setItem('isAuth', this.state.isAuth);
}

请注意,sessionStorage 中的数据始终是字符串,任何不是字符串的内容(例如布尔值)都将转换为字符串,因此您应该:

this.state = { isAuth: sessionStorage.getItem('isAuth') === "true" };