首页 文章

如何在React中刷新页面后使用localStorage来维护状态

提问于
浏览
1

每次用户登录时,即使页面重新加载,我也希望状态保持为“true” . 状态最初设置为false,(让_authed = false) . 但是当我重新加载页面时,它会返回false,这是索引页面 .

What i did 当用户登录时,我将用户的详细信息保存在localStorage中,当用户注销时,我清除了localStorage并将其设置为false . (这很好)

在setAuthed()函数中,我试图检查我在localStorage中存储的用户是否为null,它应该将authed变量保持为true .

但是当我刷新页面时它不起作用 . 有什么事,我做错了吗?帮助赞赏 .

let _authed = false;

// User logs in, set user in localStorage
saveUser(user){
  _user = user;
  localStorage.setItem('user', JSON.stringify(user))
},

//User clicks logout, set state to false 
setLogout(){
  _authed = false;
  localStorage.clear()
},

 // If there is a user in local storage, always set state to true
setAuthed(){
     if (localStorage.getItem("user") !== null) {
      _authed = true;
      }
},


getAuthed(){
  return _authed;
},

1 回答

  • 3

    您可以使用 React lifecycle 方法来读取和写入某种持久状态 . 在这里,我写了一个小例子来展示它 .

    class Root extends React.Component {
      state = {
        isLoggedIn: false
      }
      
      componentDidMount () {
        const persisState = localStorage.get('rootState');
        
        if (persistState) {
          try {
            this.setState(JSON.parse(pesistState));
          } catch (e) {
            // is not json
          }
        }
      }
      
      componentWillUnmount () {
        localStorage.set('rootState', JSON.stringify(this.state);
      }
    
      render () {
        return (
          <div>
            {this.props.children}
          </div>
        )
      }
    }
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
    

相关问题