简体   繁体   English

为什么React setState可以是异步的?

[英]Why React setState can be asynchronous?

I am aware setState can be synchronous or asynchronous: 我知道setState可以是同步的或异步的:

setState() does not immediately mutate this.state but creates a pending state transition. setState()不会立即改变this.state,但会创建挂起状态转换。 Accessing this.state after calling this method can potentially return the existing value. 调用此方法后访问this.state可能会返回现有值。

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. 无法保证对setState的调用进行同步操作,并且可以对调用进行批处理以提高性能。

Right, and I understand the function executes a few things: 是的,我理解该函数执行一些事情:

  • Update the actual value in the state 更新状态中的实际值
  • Update the virtual and real DOM as needed with the new state values 使用新的状态值根据需要更新虚拟和真实DOM

But what I'm trying to figure out is why this is sometimes synchronous and sometimes asynchronous? 但我想弄清楚的是为什么这有时是同步的,有时是异步的? What happens behind the scene? 现场背后会发生什么? Why can't it be always synchronous? 为什么不能总是同步?

Thanks. 谢谢。

Your state changes may come from many sources (depending on your app) and each state change in the component is scheduled in a queue. 您的状态更改可能来自许多来源(取决于您的应用程序),并且组件中的每个状态更改都安排在队列中。 So if you do a this.setState() in your component then it waits, allong with all other potential setStates for this component to be resolved. 因此,如果在组件中执行this.setState(),那么它将等待,并且可以解析此组件的所有其他可能的setStates。 And it might just happen the when you do something like this.setState({ value: this.state.value + 1 }) and expect outcome Then this operation is waiting to be resolved and if during that wait another operation os state change has happened then we will be operating on the newest this.stare.value, leading to unexpected returns. 当你执行类似this.setState({value:this.state.value + 1})之类的操作并且期望结果时,可能会发生这种情况然后这个操作正在等待解决,如果在那个等待期间另一个操作os状态发生了变化那么我们将在最新的this.stare.value上运行,导致意想不到的回报。 In generall, when I'm dealing with state changes that are based on previous state then I'm changin state this way: this.setState((prevState) => prevState.value + 1) this means I'm pasing the state that I have currently and make modifications according to this remembered state instead of having to rely on this.state. 通常,当我处理基于先前状态的状态更改时,我会以这种方式改变状态:this.setState((prevState)=> prevState.value + 1)这意味着我正在调整状态我目前根据这个记忆状态进行修改,而不是依赖于this.state。

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

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