react中setState是异步还是同步?

174 阅读1分钟

WX20220109-181430@2x.png

Componet
class Component {
    constructor() {
        this.$updater = new Updater(this)
    }
    setState(partialState) {
        this.$updater.addState(partialState)
    }
}
Updater
class Updater {
    constructor(instance) {
        this.instance = instance // 组件Component
        this.pendingState = []
    }
    addState(partialState) {
        // 将状态临时存在更新器中
        this.pendingState.push(partialState)

        // 是否为批量更新
        updateQueue.isBatchingUpdate
        ? updateQueue.add(this)
        : this.updateComponent
    }
  
    updateComponent() {
        const { pendingState } = this
        if (pendingState.length > 0) {
            ......
        }
    }
}
updateQueue
let updateQueue = {
    isBatchingUpdate = false // 默认为false,在事件合成中设置为true
    updaters = []

    add(updater) {
        this.updaters.push(updater)
    }

    batchUpdate() { // 事件合成中执行
        let updater
        while(updater = this.updater.shift()) { // 弹射出去
            updater.updateComponent()
        }
        // 重置批量更新
        this.isBatchingUpdate = false
    }
}

事件合成中先是将isBatchingUpdate设置为true,然后执行事件处理函数,最后调用批量更新updateQueue.batchUpdate()