简体   繁体   English

在React状态对象中更改布尔属性

[英]Changing boolean attribute within a React state object

I'm trying to update a boolean attribute inside a state object, and I'm having some trouble. 我正在尝试更新状态对象内的布尔属性,但遇到了一些麻烦。 Here is what I'm attempting to do: 这是我正在尝试做的事情:

this.setState(
  prevState => ({
    selectedGrocery: {
      ...prevState.selectedGrocery,
      checked: !prevState.checked
    }
  }),
  () => {
    console.log(this.state.selectedGrocery);
  }
);

State selectedGrocery.checked is initialized as false , and when I call the above code, it changes to true , but the next time the code is called, it doesn't change back to false . 状态selectedGrocery.checked初始化为false ,当我调用上述代码时,它更改为true ,但是下次调用该代码时,它不会更改回false Thanks in advance! 提前致谢!

You need to use prevState.selectedGrocery.checked in order to use the correct property. 您需要使用prevState.selectedGrocery.checked才能使用正确的属性。

this.setState(
  prevState => ({
    selectedGrocery: {
      ...prevState.selectedGrocery,
      checked: !prevState.selectedGrocery.checked
    }
  }),
  () => {
    console.log(this.state.selectedGrocery);
  }
);

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

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