我知道状态允许我们创建动态和交互的组件,但是我想深入了解状态。
有人可以通过一个真实的例子来帮助我理解React中的状态吗?
import React from 'react'; class App extends React.Component { state = { count: 0 }; render() { return ( <div> <h1>Hello world</h1> <h2>Count: {this.state.count}</h2> <button onClick={() => this.setState(state => ({ count: state.count + 1 }))} > + </button> <button onClick={() => this.setState(state => ({ count: state.count - 1 }))} > - </button> </div> ); } } export default App;
在上面的代码中,它有一个state带有property/state:count 的对象。
state
property/state
状态可以简单地理解为特定组件/应用在该时间点的值。在上面的示例中,当应用首次运行时,该应用处于状态count === 0
count === 0
如我们所见,有两个按钮+,-它们使用来更新值this.setState,它只是更新应用计数的“状态”,并且只要状态改变,应用都会重新渲染
+
-
this.setState