简体   繁体   English

反应布尔值的setState不更新

[英]React setState of boolean value not updating

New to React, trying to update the state of an object where on property already has a set boolean value. React的新功能,尝试更新on属性已经具有设置布尔值的对象的状态。 However, it seems like the state is not updating. 但是,状态似乎没有更新。

I understand that state is update asynchronously, maybe that could coming into play here? 我知道状态是异步更新的,也许可以在这里发挥作用? I don't believe I can use the setState method that takes an object and callback function because I need access the the previous state. 我不相信我可以使用带有对象和回调函数的setState方法,因为我需要访问以前的状态。

Here is my initial state: 这是我的初始状态:

items: [
    {
        id: 0,
        title: 'Dev Grub',
        selected: false
    },
    ...
]

And here is my event handler: 这是我的事件处理程序:

handleCardClick(id, card) {
    this.setState((preState, props) => ({
        [preState.items[id].selected]: [preState.items[id].selected] ? false : true
    }));

    console.log('new state: ', this.state.items[id].selected);

}

I've also tried this instead of the ternary: ![card.selected] 我也尝试过此方法,而不是三元方法: ![card.selected]

updating just a property at the second level of the state won't work. 仅在状态的第二级更新属性不会起作用。 use something like below: 使用如下内容:

handleCardClick(id, card) {
    let items = [...state.items];
    items[id].selected = items[id].selected ? false : true
    this.setState(() => ({
        items
    }));
}

React setState doesn't work this way, it doesn't update state right away but rather enqueues the change to update it at some point in the future. React setState不能以这种方式工作,它不会立即更新状态,而是将更改加入队列以在将来的某个时刻进行更新。

If you want to do something as soon as the state has been updated you can use callback parameter 如果您想在状态更新后立即进行操作,则可以使用回调参数

this.setState((preState, props) => ({
    [preState.items[id].selected]: [preState.items[id].selected] ? false : true
}), () => console.log('new state: ', this.state.items[id].selected);)

See docs on setState 请参阅有关setState的文档

setState is async, you console log after the state has been changed like ths setState是异步的,您可以在状态更改后控制台日志,例如:

handleCardClick = (id, card) => {
  this.setState(
    {
      [this.state.items[id].selected]: [this.state.items[id].selected]
        ? false
        : true,
    },
    () => console.log('new state: ', this.state.items[id].selected),
  );
};

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

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