setState更新状态的两种写法
(1)setState(stateChange,[callback])------对象式的setState
- stateChange为状态改变对象(该对象可以体现出状态的更改)
- callback是可选的回调函数,他在状态更新完毕、界面也更新后(render调用后)才被调用
import React, { Component } from 'react'
export default class Demo extends Component {
state={count:0}
add=()=>{
// 对象式setState
//1.获取原来的count值
const {count}=this.state;
//2.更新状态
this.setState({count:count+1},()=>{
console.log(this.state.count)
})
}
render() {
return (
<div>
<h1>当前求和为:{this.state.count}</h1>
<button onClick={this.add}>点我+1</button>
</div>
)
}
}
(2)setState(updater,[callback]) ------函数式的setState
- updater为返回stateChange对象的函数
- updater可以接收到state和props
- callback是可选的回调函数,他在状态更新、界面也更新后(render调用后)才被调用。
import React, { Component } from 'react'
export default class Demo extends Component {
state={count:0}
add=()=>{
// 函数式setState
this.setState((state,props)=>({count:state.count+1}),()=>{
console.log(this.state.count)
})
}
render() {
return (
<div>
<h1>当前求和为:{this.state.count}</h1>
<button onClick={this.add}>点我+1</button>
</div>
)
}
}
总结:
1.对象式的setState是函数式的setState的简写方式(语法糖)
2.使用原则:
(1)如果新状态不依赖于原状态 ===> 使用对象方式
(2)如果新状态依赖于原状态 ===> 使用函数方式
(3)如果需要在setState()执行后获取最新的状态数据,要在第二个callback函数中读取。
本文介绍了React中setState方法的两种写法:对象式和函数式,并分别说明了其适用场景和回调机制。
489

被折叠的 条评论
为什么被折叠?



