Calling setState in a loop only updates state 1 time

前端 未结 5 2231
故里飘歌
故里飘歌 2020-11-27 21:56

Is there a reason that calling setSate() in a loop would prevent it from updating the state multiple times?

I have a very basic jsbin that highlights th

5条回答
  •  [愿得一人]
    2020-11-27 22:17

    From the React Docs:

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

    Basically, don't call setState in a loop. What's happening here is exactly what the docs are referring to: this.state is returning the previous value, as the pending state update has not been applied yet.

提交回复
热议问题