在react中,想要修改一个状态会使用到setState函数,它是一个异步函数。
setState函数除了接收对象,还接收函数。
多次调用setState()传入对象
count默认为0,当我们传入对象
this.setState({count:1}, ()=>{console.log(this.state.count) })
this.setState({count:2}, ()=>{console.log(this.state.count) })
其实控制台会打印两个2。
分析:
当我们多次调用setState,react不会重复去做‘set-state’的动作,而是将我们传递的对象合并为一个新的对象,然后再去做‘set-state’。
多次调用setState()传入函数
count 默认为0
this.setState(function(state, props) {
return {
count: state.count + 1
}
})
this.setState(function(state, props) {
return {
count: state.count + 1
}
})
结果为 count 变为2
分析:
当setState接收函数的时候,它会将传入的函数放进一个队列,依次执行,而不是将其合并。
setState异步更新
当我们调用setState时,会执行enqueueSetState方法对partialState和_pendingStateQueue更新队列进行合并操作,最终通过enqueueUpdate执行state更新。
视图更新
perfromUpdateIfNecessary方法获取_pendingElement,_pendingStateQueue,_pendingForceUpdate,并且调用receiveComponent和updateComponent方法进行组件更新。
网友评论