gpt4 book ai didi

javascript - React 组件实例属性和状态属性有什么区别?

转载 作者:数据小太阳 更新时间:2023-10-29 05:05:04 36 4
gpt4 key购买 nike

考虑下面的例子

class MyApp extends Component {
counter = 0;
state = {
counter: 0
};
incrementCounter() {
this.counter = this.counter + 1;
this.setState({
counter: this.state.counter + 1
});
}
render() {
return <div>
<p>{this.counter} and {this.state.counter}</p>
<button onClick={this.incrementCounter}>Increment</button>
</div>
}
}

当我点击按钮时,我看到 this.counter 和 this.state.counter 都显示了增加的值

我的问题是为什么我必须使用状态?尽管 React 能够重新渲染所有实例属性

counter = 0;
incrementCounter() {
this.counter = this.counter + 1;
this.setState({});
}

在上面的代码片段中,只需调用 this.setState({}) 就可以了,那我为什么要使用 this.state 属性来存储我的组件状态?

最佳答案

stateinstance properties 有不同的用途。虽然使用空参数调用 setState 将导致渲染并反射(reflect)更新的实例属性,但状态可用于更多功能,例如在 shouldComponentUpdate 中比较 prevStatecurrentState 来决定是否要渲染,或者在像 componentDidUpdate 这样的生命周期方法中你可以根据状态变化采取行动。

state 是 react 用于特殊目的的特殊实例属性。同样在 setState 中,出于性能原因,状态更新是批处理的,并且状态更新是异步发生的,这与同步发生的类变量更新不同。类变量不具备这些功能。

此外,当您将类变量作为 prop 提供给组件时,此类变量的更改无法在子组件的生命周期方法中区分,除非您自己创建该变量的新实例。 React 已经使用 state 属性为您完成了。

关于javascript - React 组件实例属性和状态属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374946/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com