主题
State
定义 & 使用 State
jsx
import { Component } from 'react'
class View extends Component {
state = { count: 0 }
render() {
const { count } = this.state
return (
<div>
<h1>{count}</h1>
</div>
)
}
}
jsx
import { Component } from 'react'
class View extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
render() {
const { count } = this.state
return (
<div>
<h1>{count}</h1>
</div>
)
}
}
设置 State
在类组件中,只能通过 this.setState()
来更新 state
,不能直接修改。
对象式
适用于不依赖上一个状态的情况:
js
this.setState({ count: 100 })
函数式
当需要基于上一次状态进行更新时,必须使用函数式 setState:
js
this.setState(prevState => ({
count: prevState.count + 1,
}))
这个写法是安全的,因为 React 的 setState
是异步批量处理的。
示例:点击计数器
jsx
class Counter extends Component {
state = { count: 0 }
handleClick = () => {
this.setState(prevState => ({ count: prevState.count + 1 }))
}
render() {
return (
<>
<h1>{this.state.count}</h1>
<button onClick={this.handleClick}>+1</button>
</>
)
}
}