简体   繁体   English

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

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

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).状态最初设置为 false,(让 _authed = false)。 But when i reload the page, it goes back to false, which is the index page.但是当我重新加载页面时,它又回到了 false,也就是索引页面。

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.我做什么当用户登录时,我将用户的详细信息保存在 localStorage 中,当用户注销时,我清除了 localStorage 并将其设置为 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.在 setAuthed() 函数中,我尝试检查我存储在 localStorage 中的用户是否不为 null,它应该将 authed 变量保持为 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;
},

You can use React lifecycle methods to read and write some kind of persistent state.您可以使用React lifecycle方法来读取和写入某种持久状态。 Here I've wrote a tiny example to show it.在这里,我写了一个小例子来展示它。

 class Root extends React.Component { state = { isLoggedIn: false } componentDidMount () { const persistState = localStorage.getItem('rootState'); if (persistState) { try { this.setState(JSON.parse(persistState)); } catch (e) { // is not json } } } componentWillUnmount () { localStorage.setItem('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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM