小编典典

React的setState是异步的还是什么?

reactjs

嗯 我正在使用setState,由于某种原因,其后的代码无法访问新状态!

是什么赋予了?!


阅读 296

收藏
2020-07-22

共1个答案

小编典典

是的 它是异步的。我发布这个是因为这对于新的React用户而言并不是立即显而易见的。

反应“队列”更新到组件的状态。

如果您需要执行依赖于新状态更改的代码块,请像这样传递回调:

getInitialState: function () {
  return {
    isFinalCountdown: false,
  }
}

//blablabla

//then somewhere you got...
this.setState(
  {isFinalCountdown: true},
  function () {//<--- whoa. this solves your all your synchrosity woes!
    console.log(this.state.isFinalCountdown); //true!
  }
);

console.log(this.state.isFinalCountdown); //false!

所有这些都在文档中,这只是真正需要重申的内容,以避免新的React用户可能遇到的常见错误。

签出:https
//facebook.github.io/react/docs/component-
api.html#setstate
2020-07-22