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

查看:29
本文介绍了在循环中调用 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文档:

setState() 将更改加入组件状态并告诉 React 该组件及其子组件需要使用更新后的状态重新渲染.这是您用来更新用户界面以响应事件处理程序和服务器响应的主要方法.

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.

setState() 视为更新组件的请求而不是立即命令.为了更好的感知性能,React 可能会延迟它,然后一次更新多个组件.React 不保证立即应用状态更改.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState() 并不总是立即更新组件.它可能会批量更新或推迟更新.这使得在调用 setState() 后立即读取 this.state 成为一个潜在的陷阱.

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.

基本上,不要在循环中调用 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天全站免登陆