简体   繁体   中英

this.setState() in callback of this.setState()

Can I explicitly call this.setState() in the definition of the callback passed to this.setState()?

this.setState(
 {
   openA:true 
 }, 
 () => {
   this.setState({
     openB: false
   })
 } 
)

This can be done, and this will result in 2 re-renders instead of 1. Usually there is no need to do this.

If setState are independent, it can be:

this.setState({ openA:true });
this.setState({ openB:false });

If updated states depend on each other, updater function should be used:

this.setState({ openA:true });
this.setState(state => ({ openB: !state.openA }));

Yes. It will run it after the first setState is complete.

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