javascript - SetState callback not waiting for state to update - Stack Overflow

Acording to the setState documentation the callback should fire after the new state has been set. Howev

Acording to the setState documentation the callback should fire after the new state has been set. However, my code

console.log(school);
this.setState({ lastSegment: school },console.log(this.state.lastSegment));

Prints:

Middle
Grammar

Since school="Middle" why is the setState callback printing "Grammar" (which is the previous value of this.state.lastSegment)

Acording to the setState documentation the callback should fire after the new state has been set. However, my code

console.log(school);
this.setState({ lastSegment: school },console.log(this.state.lastSegment));

Prints:

Middle
Grammar

Since school="Middle" why is the setState callback printing "Grammar" (which is the previous value of this.state.lastSegment)

Share Improve this question asked Jul 26, 2017 at 23:34 AdamGAdamG 2,6303 gold badges25 silver badges39 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

The callback is a function passed to another function as an argument and sometimes referred as anonymous function which means a function without a name, so you're executing the console.log in place, and returning the value as the second argument to setState. You want to pass in a function, not the result of console.log.

this.setState({ lastSegment: school }, () => { 
  console.log(this.state.lastSegment); 
});

or using ES5 syntax:

this.setState({ lastSegment: school }, function() { 
  console.log(this.state.lastSegment); 
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742354068a4428089.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信