简体   繁体   中英

ReactJs setState callback not working

I have a strange behavior with the setState callback, hopefully somebody can help. The callback just isn't fired.

Here is what I do:

 this.setState( (prevState, props) => { return { first: obj, questions: [] } }, this.changeStateCb );

For some reason the changeStateCb function is never being called. Same problem when I change it to:

 this.setState( (prevState, props) => { return { first: obj, questions: [] } }, () => console.log(this.state) );

I just updated from v15.x to 16.2.0

Do you have a demo? I just put up a simple working example , and it seems to run just fine under React 16.2.0 . Do note though that the optional callback should be used sparingly . As the docs mention, it will be executed once setState is completed and the component is re-rendered. So, a better place to do the logic in this.changeStateCb would be inside componentDidUpdate .

I just had the same issue happen to me. A simple console.log('test') in the callback wouldn't even run. It turns out I had to delete my /dist folder in the build directory. I am using Type Script and webpack and upgraded from a .net core template.

Have the same issue. The callback is not invoked. I traced it to React min code and the function to enqueueSetState does not accept the callback even though it is passed in from internal React code...so code explains why it is not called. But this used to work just fine in React 15.x - what's going on...I am trying React 16.8.4

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