为什么 React 必须使用 setState 进行状态更新? [英] Why does React have to use setState for state update?

查看:44
本文介绍了为什么 React 必须使用 setState 进行状态更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 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屋!

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