为什么 React 必须使用 setState 进行状态更新? [英] Why does React have to use setState for state update?
问题描述
为什么 react 必须使用 setState 更新状态(树协调).而不是简单地初始化 this.state.color = 'red';假设颜色的先前值为绿色".
Why does react have to update state (tree reconciliation) using setState. And not by simply initializing this.state.color = 'red'; supposing that previous value for color is 'green'.
推荐答案
React 就是这样构建的.
This is how React is built.
这个概念是你不应该像这样改变状态:
The concept is that you should not change the state mutably, like this:
this.state.color = 'red';
相反,您应该使用 setState:
Instead, you should use setState:
this.setState({color: 'red'});
这背后的想法是为了跟踪状态的变化,然后根据变化重新渲染组件,你必须使用 setState,因为在 setState 之后,渲染函数被触发.
The idea behind that is that in order to track changes in state and than re-render the component according to the changes, you have to use setState, because after setState, the render function is triggered.
这篇关于为什么 React 必须使用 setState 进行状态更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!