简体   繁体   中英

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

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]

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.

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 is async, you console log after the state has been changed like ths

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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