简体   繁体   English

如何将状态存储在本地存储中以作出反应?

[英]How to store a state in localstorage for react?

I'm trying to store my checkbox checked value into the localstorage in my react app. 我正在尝试将我的复选框检查值存储到我的React应用程序中的localstorage中。 But everytime I store, it will store a previous state. 但是每次我存储时,它将存储以前的状态。 Below is my code: 下面是我的代码:

For render side: 对于渲染面:

  render () {   
    return (
                      <Checkbox
                        checked={this.state.checkedCheckpoint}
                        onChange={() => this.onChange('checkpoint')}
                      >
                      </Checkbox>
          )

For the onchange method: 对于onchange方法:

  onChange (value){
    const { checkedCheckpoint } = this.state

    if (value === 'checkpoint')
    {
      if (checkedCheckpoint)
      {
        this.setState({checkedCheckpoint : false})
        console.log(checkedCheckpoint)
      }
      else
      {
        this.setState({checkedCheckpoint : true})
        console.log(checkedCheckpoint)
      }
    }
    localStorage.setObject('checkedCheckpoint', checkedCheckpoint)

What I mean by previous state is: If I initialize my checkpoint to be true, after I unchecked, I should get checkpoint: false right? 我以前的状态是什么意思:如果我将检查点初始化为true,那么在取消检查后,我应该得到checkpoint: false对吗? But I get checkedCheckpoint: true . 但是我得到了checkedCheckpoint: true If I checked it, I should get checkedCheckpoint: true right? 如果我检查了它,就应该检查一下checkedCheckpoint: true吗? I will get checkedCheckpoint: false . 我将获得checkedCheckpoint: false Seems like it will always follow the previous state in localstorage. 似乎它将始终遵循本地存储中的先前状态。 Anyone knows what's wrong? 有人知道怎么了吗?

You need to pass whatever logic you want to execute post state change as a second argrument to this.setState() 您需要将要执行后状态更改的任何逻辑作为第二个参数传递给this.setState()

example: 例:

state = {
    name: 'Johnny'
}

someMethod = () => {
     this.setState({name: 'Tim'})
     doSomethingElse(this.state.name) //doSomethingElse receives Johnny
}

I think what you're looking for is 我想你要找的是

state = {
    name: 'Johnny'
}

someMethod = () => {
    this.setState({name: 'Tim'}, doSomethingElse(this.state.name))
    //doSomethingElse receives Tim
}

See the docs for setState here . 此处查看setState的文档。

You need to set it based on the new value not the old one 您需要根据新值而不是旧值进行设置

  onChange (value){
    const { checkedCheckpoint } = this.state

    if (value === 'checkpoint')
    {
      if (checkedCheckpoint)
      {
        this.setState({checkedCheckpoint : false})
        localStorage.setObject('checkedCheckpoint', false)
        console.log(checkedCheckpoint)
      }
      else
      {
        this.setState({checkedCheckpoint : true})
        localStorage.setObject('checkedCheckpoint', true)
        console.log(checkedCheckpoint)
      }
    }

React tries to batch the setState command. React尝试批处理setState命令。 It is more like an asynchronous task. 它更像是一个异步任务。 So when you execute this.setState({checkedCheckpoint : true}) it only tells react to set the state of 'checkedCheckpoint' to true but it does not execute that command at that moment. 因此,当您执行this.setState({checkedCheckpoint:true})时,它只会告诉将“ checkedCheckpoint”的状态设置为true的反应,但此时不会执行该命令。 So basically when you are trying to set your localStorage variable it is still the previous state. 因此,基本上,当您尝试设置localStorage变量时,它仍然是先前的状态。

Try setting your new state in a variable like this. 尝试在这样的变量中设置新状态。

onChange (value){
var newState;
const { checkedCheckpoint } = this.state

if (value === 'checkpoint') {
  if (checkedCheckpoint) {
    newState = false;
    console.log(newState);
  }
  else {
    newState = true;
    console.log(newState);
  }
  this.setState({checkedCheckpoint : newState});
  localStorage.setObject('checkedCheckpoint', newState);
}

Perhaps, you can do something like this: 也许,您可以执行以下操作:

<Checkbox
    checked={this.state.checkedCheckpoint}
    onChange={() => this.setState((prevState) => ({checkedCheckpoint: !prevState.checkedCheckpoint}),
    () =>{console.log(this.state.checkedCheckpoint)})}
>
</Checkbox>           

Also, the issue with your code was that it doesn't account for the fact that state in react setState happens asynchronously . 另外,您的代码的问题在于,它没有考虑到react setState中的state 异步发生的事实。 As a consequence, it'll always show a previous state while logging. 因此,它在记录时将始终显示以前的状态。

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

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