平常抄书之一次性弄懂setState

1.前言

React是经过管理状态来实现对组件的管理。那么React是如何控制组件的状态,又是如何利用状态来管理组件的呢?数组

在React中是经过this.setState()来更新state。当调用this.setState()的时候,React会从新调用render方法来从新渲染UI。bash

2.异步setState

setState是一个异步操做。setState是经过队列机制实现state 更新。当执行setState会将须要更新的state合并后放入 状态队列,而不会马上更新this.state。app

//将新的state合并到状态更新队列中
var nextState = this._processPendingState(nextProps, nextContent)
//根据更新队列和shouldComponentUpdate的状态来判断是否须要更新组件
var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext)
复制代码

3.setState循环调用风险

不要在shouldComponentUpdatecomponentWillUpdate中调用setState,否则会出现死循环。异步

在调用setState时,实际上回执行enqueueSetState方法,并对partialState_pendingStateQueue更新队列进行合并操做。最终经过enqueueUpdate执行state更新。ui

performUpdateIfNecessary方法会获取 _pendingElement_pendingStateQueue_pendingForceUpdate,并调用receiveComponentupdateComponent方法进行组件更新。this

若是在componentWillUpdateshouldComponentUpdate中调用setState,此时 _pendingStateQueue!==nullperformUpdateIfNecessary会调用updateComponent进行组件更新,而updateComponent又会调用shouldComponentUpdateshouldComponentUpdate,这样就会致使循环调用。spa

接下来看下setState源码:prototype

ReactComponent.prototype.setState = function(partialState, callback) {
    //调用enqueueSetState,将setState事务放进队列中
    //partialState能够传object,也能够穿function,他会产生新的state以一种
    //Object.assign()的方式跟旧的state进行合并。
    this.updater.enqueueSetState(this, partialState)
    if(callback) {
        this.updater.enqueueCallback(this, callback, 'setState')
    }
}

//实际经过enqueueSetState执行。
//1. 将新的state放进数组
//2. 用enqueueUpdate来处理将要更新的实例对象
enqueueSetState: function(publicInstance, partialState) {
    //获取当前组件的instance
    var internalInstance = getInternalInstanceReadyForUpdate(
        publicInstance,
        'setState'
    )
    
    if(!internalInstance) return
    
    //更新队列合并操做
    var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = [])
    
    //partialState能够理解为以前的state
    queue.push(partialState)
    //最终经过enqueueUpdate更新,将要更新的component instance放入一个队列
    enqueueUpdate(internalInstance)
}

//若是存在_pendingElement、_pendingStateQueue和_pendingForceUpdate,则更新组件
performUpdateIfNecessary: function(transaction) }
    if(this._pendingElement != null) {
       ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context) 
    }
    if(this._pendingStateQueue !== null || this._pendingForceUpdate) {
        this.updateComponent(transaction, this._currentElement, this._currentElement, this._context)
    }
    
}
复制代码

4.setState调用栈

function enqueueUpdate(component) {
    ensureInjected();
    
    //若是不处于批量更新模式
    if(!batchingStrategy.isBatchingUpdates) {
        batchingStrategy.batchedUpdates(enqueueUpdate, component)
        return
    }
    //若是处于批量更新模式
    dirtyComponents.push(component)
}
复制代码
//batchingStrategy
var ReactDefaultBatchingStrategy = {
    isBatchingUpdates: false,
    batchedUpdates: function(callback, a, b, c, d, e) {
        var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates
        ReactDefaultBatchingStrategy.isBatchingUpdates = true
        
        if(alreadyBatchingUpdates) {
            callback(a,b,c,d,e)
        }else {
            transaction.perform(callback, null, a, b, c, d, e)
        }
    }
}
复制代码

batchedUpdate中有一个transaction.perform调用。这就是事务的概念。3d

5. 事务

事务就是将须要执行的方法使用wrapper封装起来,再经过事务提供的perform方法执行。而在perform以前,先执行所wrapper中的initialize方法,执行完perform以后再执行全部的close方法。一组initialize以及close方法称为一个wrappercode

到实现中,事务提供一个mixin方法供其余模块实现本身须要的事务。而要使用事务的模块除了须要把mixin混入本身的事务实现以外,还要额外实现一个抽象getTransactionWrap接口。这个接口用来获取须要封装的前置方法(initialize)和收尾方法(close)。所以它须要返回一个数组的对象,这个对象分别有key为initializeclose的方法。

var Transaction = require('./Transaction')
//咱们本身定义的事务
var MyTransaction = function() {}

Object.assign(MyTransaction.prototype, Transaction.mixin, {
    getTransactionWrap: function() {
        return [{
            initialize: function() {
                console.log("before method perform")
            },
            close: function() {
                console.log("after method perform")
            }
        }]
    }
})

var transaction = new MyTransaction()
var testMethod = function() {
    console.log('test')
}
transaction.perform(testMethod)
//打印结果以下:
//before method perform
//test
//after method perform
复制代码
相关文章
相关标签/搜索