本文介绍了在React中刷新页面后如何使用localStorage维护状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我做了什么当用户登录时,我将用户的详细信息保存在localStorage中,当用户注销时,我清除了localStorage并将其设置为false.(效果很好)

What i didWhen 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)

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

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;
},

推荐答案

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

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 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>

这篇关于在React中刷新页面后如何使用localStorage维护状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:49