class类组件中
可以通过两种方式来实现setState的回调
- setState加入第二个参数作为
回调函数
this.setState(
{ count: 1 },
() => { // 回调函数
console.info(this.state.count)
}
)
- 利用
componentDidMount生命周期钩子
xxx() {
this.setState({ count: 1 })
}
componentDidMount() {
console.info(this.state.count)
}
刚好,hooks中的useEffect可以模拟出componentDidMout
函数组件
- 利用useEffect
function Com() {
const [count, setState] = useState(0)
xxx => setState(1)
useEffect(() => {
console.info(count)
}, [count])
}