简体   繁体   English

如何在反应时从本地存储中检索状态

[英]How to retrieve state from local storage on react

Guys is there anyway to get the state from localstorage?无论如何,伙计们有没有从本地存储中获取状态?

I Read some articles and some questions here, but none helps, how Could I load my state saved on the local storage?我在这里阅读了一些文章和一些问题,但没有任何帮助,我如何加载保存在本地存储上的状态? I Don't want to set the state field by field, there's a lot of it, but I have 3 components that has functions of previous and next , so on the previous I want to load the state to be the same of that session.我不想按字段设置状态字段,它有很多,但是我有 3 个组件具有前一个和下一个功能,所以在前一个我想加载状态与该会话相同。

I'm trying this:我正在尝试这个:

  var JSON1= JSON.stringify(this.state)
  localStorage.setItem('JSON1', JSON1)

And on the constructor在构造函数上

   constructor(props) {
    super(props);
    let JSONSTOR = JSON.parse(localStorage.getItem("JSON1"))
    var newST = this.state
    newST = JSON.parse(localStorage.getItem("JSONCLIENTE 1"));
    this.setState(newST)

} }

But it's not working, is there anyway to do this?但它不起作用,有没有办法做到这一点?

As Fernando Ramirez suggested, you could use Redux.正如 Fernando Ramirez 建议的那样,您可以使用 Redux。 Redux also takes a state parameter so you can set the initial state. Redux 还带有一个 state 参数,因此您可以设置初始状态。 There are examples of how to save Redux state to localStorage and then also re-load it from localStorage.有一些示例说明如何将 Redux 状态保存到 localStorage,然后从 localStorage 重新加载它。 Here's a tutorial from the creator of Redux Dan Abramov .是 Redux Dan Abramov 的创建者的教程

The thing you are trying to do looks correct, you just have some mistakes in your flow.您尝试做的事情看起来是正确的,只是您的流程中存在一些错误。

This should work for your case:这应该适用于您的情况:

var JSON1 = JSON.stringify(this.state);

localStorage.setItem("JSON1", JSON1);

And then in your constructor you can reload the state from localStorage:然后在您的构造函数中,您可以从 localStorage 重新加载状态:

constructor(props) {
    super(props);

    this.state = JSON.parse(localStorage.getItem("JSON1"));
}

I think the best way to achieve this could be using Redux.我认为实现这一目标的最佳方法可能是使用 Redux。 With Redux you can handler the global state of your app.使用 Redux,您可以处理应用程序的全局状态。

Here's Redux official documantation:这是 Redux 官方文档:

Redux终极版

You can easily load localStorage data into React using the lifecycle methodcomponentDidMount :您可以使用生命周期方法componentDidMount轻松地将localStorage数据加载到 React 中:

componentDidMount() {
  // Load localStorage data into state (if it exists)
  let data = JSON.parse(localStorage.getItem("yourData"));
  if (data) {
    this.setState(data);
  }
}

Keep in mind that the data retrieved from localStorage is a string that should have an object like appearance, this way you can convert it into a valid object with JSON.parse() , this in turns allows you to successfully set the local state in the React app.请记住,从localStorage检索到的数据是一个应该具有类似外观的对象的字符串,这样您就可以使用JSON.parse()将其转换为有效对象,这反过来又允许您在反应应用程序。

Working example here 这里的工作示例

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

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