在循环中调用 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.
相关文章