在循环中调用setState仅更新状态1次 [英] Calling setState in a loop only updates state 1 time

查看:542
本文介绍了在循环中调用setState仅更新状态1次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有理由在循环中调用 setSate()会阻止它多次更新状态?

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

我有一个非常基本的jsbin ,突出了我所看到的问题。有两个按钮。一个将状态计数器更新为1.另一个在循环中调用One的基础函数 - 这似乎会多次更新状态。

I have a very basic jsbin that highlights the problem I am seeing. There are two buttons. One updates the state's counter by 1. The other calls the underlying function of One in a loop -- which seemingly would update the state multiple times.

我知道几个解决方案对于这个问题,但我想确保我首先理解这里的潜在机制。为什么不能在循环中调用 setState ?我是否因为阻止了预期的效果而编码笨拙?

I know of several solutions to this problem but I want to make sure that I am understanding the underlying mechanism here first. Why can't setState be called in a loop? Do I have it coded awkwardly that is preventing the desired effect?

推荐答案

来自 React Docs


setState()不会立即改变this.state但会创建
挂起状态转换。调用此
方法后访问this.state可能会返回现有值。对于调用setState的同步操作没有
保证,并且可以为了性能增益调用
批次。

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.

基本上,不要在循环中调用 setState 。这里发生的正是文档所指的内容: this.state 返回之前的值,因为还没有应用挂起状态更新。

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.

这篇关于在循环中调用setState仅更新状态1次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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