React的setState是异步的还是什么? [英] Is React's setState asynchronous or something?

查看:96
本文介绍了React的setState是异步的还是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hmm. I'm using setState and for some reason the code following it doesn't have access to the new state!

有什么用?!

推荐答案

是的.它是异步的.我之所以这样发布是因为,这对于新的React用户而言并不是立即显而易见的.

Yeap. It's asynchronous. I'm posting this because this isn't really immediately obvious to new React users.

将队列"更新为组件状态.

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!

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

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.

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

这篇关于React的setState是异步的还是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆