How can i use localStorage to maintain state after a page refresh in React

三世轮回 提交于 2020-02-05 05:17:48

问题


Each time a user logs in, i want the state to remain at 'true' even if there is a page reload. The state is set initially to false, (let _authed = false). But when i reload the page, it goes back to false, which is the index page.

What i did When the user logs in, i save the user's details in localStorage and when the user logs out, i cleared the localStorage and i set it to false. (this works fine)

In the setAuthed() function, i tried to check if the user i stored in localStorage is not null, it should keep the authed variable to true.

But its not working when i refresh the page. Is there anything, i am doing wrong? Help appreciated.

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:


You can use React lifecycle methods to read and write some kind of persistent state. Here I've wrote a tiny example to show it.

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>


来源:https://stackoverflow.com/questions/45111159/how-can-i-use-localstorage-to-maintain-state-after-a-page-refresh-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!