最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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); 
});
发布评论

评论列表(0)

  1. 暂无评论