哪种方法在React中更新组件的状态是好的 [英] Which approach is good to update State of the Component in React
问题描述
这是CodePen中有效的示例.
Here's the working example in CodePen.
它具有一个在ON
和OFF
在反应文档中,它使用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屋!