react中setState()是异步的还是同步的,如何控制?
之前一直在做vue开发,可能对vue了解的多一些,但是近期想开始整明白react背后的事情。 仅仅适用于react18版本之前
this.state.count += 1 不会触发数据更新
handleClickDemo = () => {this.state.count += 1 // 该代码仅在作用域范围之内有效 不会触发页面更新渲染console.log(this.state.count) // 第1次点击 结果为1 // 第1次点击 结果为3this.setState({ count: this.state.count + 1 }) // setState才会更新数据 触发页面渲染this.state.count += 5// 该行不会改变state中数据}
setState()的使用说明
setState(updater, [callback])
一、参数1 updater
功能:更新数据,渲染UI
1.1、更新数据
注意:使用该语法时,注意:【后面的setState()不要依赖于前面的setState()更新后的数据】
可能(异步情况下
,什么时候为异步/同步,后面会有介绍)多次调用setState(),但只会触发一次重新渲染
handleClick = () => {console.log("count", this.state.count) //0this.setState({ count: this.state.count + 1 })console.log("count", this.state.count) //0this.setState({ count: this.state.count + 1 })console.log("count", this.state.count) //0this.setState({ count: this.state.count + 1 })console.log("count", this.state.count) //0// 页面渲染结果为: 1
}
1.2、推荐语法【如果有两个setState()方法,第二个setState()里面的数据依赖第1个setState()更新后的数据】
推荐:使用setState((state, props) => {})
参数state:表示最新的state
参数props: 表示最新的props
注意:这种语法可能是异步更新
state的,但是都能获取到最新数据
handleClickFn = () => {console.log("count", this.state.count) //0this.setState((preState, props) => {return {// 0 + 1count: preState.count + 1}})console.log("count", this.state.count) //0this.setState((preState, props) => {return {// 1 + 1count: preState.count + 1}})console.log("count", this.state.count) //0this.setState((preState, props) => {return {// 2 + 1count: preState.count + 1}})console.log("count", this.state.count) //0// 页面渲染结果为:3
}
二、参数2 callback
场景:在状态更新后并且页面完成重新渲染后
立即执行某个操作
this.setState((state, props) => { },() => {console.log('这个回调函数会在状态更新后并且页面完成重新渲染后立即执行')console.log('这里可以打印更改this.state的值', this.state.count)}
)
handleClick = () => {console.log("count", this.state.count) //0this.setState({ count: this.state.count + 1 },() => {console.log('这个回调函数会在状态更新后并且页面完成重新渲染后立即执行')console.log('1这里可以打印更改this.state的值', this.state.count) //1})console.log("count", this.state.count) //0this.setState({ count: this.state.count + 1 },() => {console.log('这个回调函数会在状态更新后并且页面完成重新渲染后立即执行')console.log('2这里可以打印更改this.state的值', this.state.count) //1})console.log("count", this.state.count) //0this.setState({ count: this.state.count + 1 },() => {console.log('这个回调函数会在状态更新后并且页面完成重新渲染后立即执行')console.log('3这里可以打印更改this.state的值', this.state.count) //1})console.log("count", this.state.count) //0// 页面渲染结果为: 1
}
handleClickFn = () => {console.log("count", this.state.count) //0this.setState((preState, props) => {return {// 0 + 1count: preState.count + 1}}, () => {console.log('这个回调函数会在状态更新后并且页面完成重新渲染后立即执行')console.log('1这里可以打印更改this.state的值', this.state.count) //3})console.log("count", this.state.count) //0this.setState((preState, props) => {return {// 1 + 1co