哪种方法在React中更新组件的状态是好的 [英] Which approach is good to update State of the Component in React

查看:311
本文介绍了哪种方法在React中更新组件的状态是好的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是CodePen中有效的示例.

Here's the working example in CodePen.

它具有一个在ONOFF

反应文档中,它使用prevState并更新了state的值

In React docs, it used prevState and updated the value of state.

    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));

当我使用以下方法时,它也会产生相同的结果.

It also produces the same result when I use the below method.

    this.setState({isToggleOn: !this.state.isToggleOn})

有人可以建议哪个是更新 State Component的好方法吗?

Could anyone suggest which one is good way and is recommended way to update the State the Component?

推荐答案

由于setState的异步特性,建议不要使用this.state获取setState中的先前状态.相反,如果必须使用以前的状态,请依赖更新程序功能方法.

Because of to the asynchronous nature of setState, it is not advisable to use this.state to get the previous state within a setState. Instead, if you have to use the previous state, rely on the updater function approach.

将setState()视为请求而不是直接命令 更新组件.为了获得更好的感知性能,React可能会 延迟它,然后在一次通过中更新几个组件.反应 不保证状态更改会立即应用. https://reactjs.org/docs/react-component.html#setstate

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. https://reactjs.org/docs/react-component.html#setstate

这篇关于哪种方法在React中更新组件的状态是好的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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