简体   繁体   English

React的setState是异步还是什么?

[英]Is React's setState asynchronous or something?

Hmm. 嗯。 I'm using setState and for some reason the code following it doesn't have access to the new state! 我正在使用setState ,由于某种原因,它后面的代码无法访问新状态!

What gives?! 是什么赋予了?!

Yeap. 叶氏。 It's asynchronous. 这是异步的。 I'm posting this because this isn't really immediately obvious to new React users. 我发布这个是因为这对新的React用户来说并不是很明显。

React "queues" updates to a component's state. 对组件的状态进行“队列”更新。

If you need to execute a code block that's dependent on the new state change, pass a callback like so: 如果需要执行依赖于新状态更改的代码块,请传递回调,如下所示:

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!

All of this is in the docs, it's just something that really needs to be reiterated to avoid those common bugs that new React users likely come across. 所有这些都在文档中,它只是需要重复的东西,以避免新的React用户可能遇到的常见错误。

Check it out: https://facebook.github.io/react/docs/component-api.html#setstate 看看: https//facebook.github.io/react/docs/component-api.html#setstate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM