简体   繁体   中英

Avoid React setState() callback loop

I am trying to set multiple state properties at same time, but since setState() is asynchronous I've to use callback, but as more properties I have to edit at one time this code becomes more & more ugly!

Is there any other good way to achieve this?

this.setState(
  {
    item_1: true
  },
  (e => {
    this.setState(
      {
        item_2: false
      },
      (e => {
        this.setState(
          {
            item_3: 'Hello World'
          }
        )
      })
    )
  })
)

It's quite possible to set them all in one go, like this:

this.setState({
    item_1: true,
    item_2: false,
    item_3: 'Foo'
});

If you still want to make certain change after state change, you can still use callback with this. like setState({obj},callback);

@HoriaComan answer is correct but to provide more info.

Yes, setState is asynchronous but asynchronous behaviour comes into play when your other input depends on the previous output,

In your case all the state values are independent. So you can directly set the state like

this.setState({
    item_1: true,
    item_2: false,
    item_3: 'Foo'
});

You will want to use a callback in case when you want to use the updated state just after setting it for instance

this.setState({
    item_1: true,
    item_2: false,
    item_3: 'Foo'
}, ()=> {
     console.log(this.state.item_1, this.state.item_2, this.state.item_3);
});

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