React的setState何时更改状态 [英] When does React's setState change the state

查看:89
本文介绍了React的setState何时更改状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在子组件中有一个函数 open(),它调用父函数 open() props ,它可以连续多次。

I have a function open() in a child component which calls the parent's function open() through props, and it could be multiple times in a row.

父函数包含这一行

this.setState({numOpen: (++this.state.numOpen)});

此行在每次增量时都有效并更新状态。

This line works and updates the state at every increment.

但之前,这一行

this.setState({numOpen: (this.state.numOpen + 1)});

跳过几个增量并打破了程序。

skipped over several increments and was breaking the program.

是否异步调用setState?如果没有,那可能是什么原因?

Does setState get called asynchronously? if not, what could be the reason for it?

推荐答案

正如@MayankShukla的重复回答所示,<$ p $ c > setState是异步的,

As the Duplicate answer by @MayankShukla indicates, setState is asynchronous,

但是添加解释和更正的方法

however Adding an explanation and a corrected approach

在下面的例子中:

this.setState({numOpen: (++this.state.numOpen)});

您正在改变状态,然后设置值,因此它可以工作,但不是正确的这样做的方法

You are mutating the state directly and then setting the value and hence it works, but is not the right way to do it

在第二种情况下

this.setState({numOpen: (this.state.numOpen + 1)});

setState 正在将值添加到当前因为它的异步性而导致出现意外行为。

setState is adding the value to the current state as you experience it leads to unexpected behaviour due to its asynchronous nature.

正确的方法是使用 prevState 回调方法

The correct way to do it is to use the prevState callback approach

 this.setState((prevState) => ({numOpen: (prevState.numOpen + 1)});

这篇关于React的setState何时更改状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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