React原始碼解析(3):元件的生命週期

fiveoneLei發表於2018-12-03

這一章可能比較長,因為這一章我會把生命週期,transaction,setState放到一起說明. 元件的生命週期分為二個部分

  1. 元件的掛載
  2. 元件的更新

元件的掛載

上一章對於元件的掛載已經做了詳細的說明,但是涉及到元件生命週期部分被略過.接下來我將對其深入解析. 元件的掛載涉及到二個比較重要的生命週期方法componentWillMountcomponentDidMount.

componentWillMount

對於componentWillMount這個函式玩過React的都知道他是元件render之前的觸發. 但是如果我再具體點呢. 是在例項之前?還是例項之後?還是構建成真實dom之前?還是構建成真實dom之前,渲染之前?估計很多人不知道吧.所以在面試的時候無論你對React有多熟,還是儘量不要說"精通"二字.(大佬除外)

componentWillMount是元件更新之前觸發,所以直接從ReactCompositeComponent.mountComponent裡面找

// this.performInitialMount

if (inst.componentWillMount) {
    debugger
    if ("development" !== "production") {
        measureLifeCyclePerf(
            function() {
                return inst.componentWillMount();
            },
            debugID,
            "componentWillMount"
        );
    } else {
        inst.componentWillMount();
    }
    // When mounting, calls to `setState` by `componentWillMount` will set
    // `this._pendingStateQueue` without triggering a re-render.
    if (this._pendingStateQueue) {
        inst.state = this._processPendingState(
            inst.props,
            inst.context
        );
    }
}
複製程式碼

程式碼在performInitialMount函式裡面,所以在例項之後,虛擬dom構建真實dom之前觸發的

componentDidMount

直接看程式碼吧

var markup;
if (inst.unstable_handleError) {
    markup = this.performInitialMountWithErrorHandling(
        renderedElement,
        hostParent,
        hostContainerInfo,
        transaction,
        context
    );
} else {
    markup = this.performInitialMount(
        renderedElement,
        hostParent,
        hostContainerInfo,
        transaction,
        context
    );
}
if (inst.componentDidMount) {
        if ("development" !== "production") {
            transaction
                .getReactMountReady()
                .enqueue(function() {
                    measureLifeCyclePerf(
                        function() {
                            return inst.componentDidMount();
                        },
                        _this._debugID,
                        "componentDidMount"
                    );
                });
        } else {
            transaction
                .getReactMountReady()
                .enqueue(
                    inst.componentDidMount,
                    inst
                );
        }
    }
複製程式碼

它是出現在markup(真實dom)之後.但是肯定不會在這裡面執行,因為在markup還沒插入到container裡面呢。回顧一下上一章的內容MountComponentIntoNode方法mountComponent之後還有個setInnerHTML(container, markup)只有這個函式執行完之後componentDidMount才能執行.

注意performInitialMount方法 看看下面的程式碼

class A extends React.Component {
    render(){
        return <K />
    }
}
<App>
    <A />
</App>
複製程式碼

this.componentDidMount的執行順序是K-->A--->App. 因為APP執行到 this.performInitialMount就開始深度遍歷了.然後執行AA又遍歷執行K. K執行完才向上執行. 瞭解了他們的執行順序我們看看

transaction
    .getReactMountReady()
    .enqueue(function() {
        measureLifeCyclePerf(
            function() {
                return inst.componentDidMount();
            },
            _this._debugID,
            "componentDidMount"
        );
    });
複製程式碼

再看看這個transaction是在哪裡生成的

var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
    /* useCreateElement */
    !shouldReuseMarkup &&
        ReactDOMFeatureFlags.useCreateElement
);
transaction.perform(
    mountComponentIntoNode,
    null,
    componentInstance,
    container,
    transaction,
    shouldReuseMarkup,
    context
);
複製程式碼

transactionReact裡面一個非常核心的功能. 出現在很多個地方,不搞清楚transtion原始碼是沒辦法讀下去的.

事務和佇列

看看官方給出的流程圖

 * <pre>
*                       wrappers (injected at creation time)
*                                      +        +
*                                      |        |
*                    +-----------------|--------|--------------+
*                    |                 v        |              |
*                    |      +---------------+   |              |
*                    |   +--|    wrapper1   |---|----+         |
*                    |   |  +---------------+   v    |         |
*                    |   |          +-------------+  |         |
*                    |   |     +----|   wrapper2  |--------+   |
*                    |   |     |    +-------------+  |     |   |
*                    |   |     |                     |     |   |
*                    |   v     v                     v     v   | wrapper
*                    | +---+ +---+   +---------+   +---+ +---+ | invariants
* perform(anyMethod) | |   | |   |   |         |   |   | |   | | maintained
* +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|-------->
*                    | |   | |   |   |         |   |   | |   | |
*                    | |   | |   |   |         |   |   | |   | |
*                    | |   | |   |   |         |   |   | |   | |
*                    | +---+ +---+   +---------+   +---+ +---+ |
*                    |  initialize                    close    |
*                    +-----------------------------------------+
 * </pre>
var TransactionImpl = {
  reinitializeTransaction: function () {
    this.transactionWrappers = this.getTransactionWrappers();
    if (this.wrapperInitData) {
      this.wrapperInitData.length = 0;
    } else {
      this.wrapperInitData = [];
    }
    this._isInTransaction = false;
  },

  _isInTransaction: false,

  getTransactionWrappers: null,

  isInTransaction: function () {
    return !!this._isInTransaction;
  },

  perform: function (method, scope, a, b, c, d, e, f) {
    !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction.') : _prodInvariant('27') : void 0;
    var errorThrown;
    var ret;
    try {
      this._isInTransaction = true;
      errorThrown = true;
      this.initializeAll(0);
      ret = method.call(scope, a, b, c, d, e, f);
      errorThrown = false;
    } finally {
      try {
        if (errorThrown) {
          try {
            this.closeAll(0);
          } catch (err) {}
        } else {
          this.closeAll(0);
        }
      } finally {
        this._isInTransaction = false;
      }
    }
    return ret;
  },

  initializeAll: function (startIndex) {
    var transactionWrappers = this.transactionWrappers;
    for (var i = startIndex; i < transactionWrappers.length; i++) {
      var wrapper = transactionWrappers[i];
      try {
        this.wrapperInitData[i] = OBSERVED_ERROR;
        this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null;
      } finally {
        if (this.wrapperInitData[i] === OBSERVED_ERROR) {
          try {
            this.initializeAll(i + 1);
          } catch (err) {}
        }
      }
    }
  },

  closeAll: function (startIndex) {
    !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : _prodInvariant('28') : void 0;
    var transactionWrappers = this.transactionWrappers;
    for (var i = startIndex; i < transactionWrappers.length; i++) {
      var wrapper = transactionWrappers[i];
      var initData = this.wrapperInitData[i];
      var errorThrown;
      try {
        errorThrown = true;
        if (initData !== OBSERVED_ERROR && wrapper.close) {
          wrapper.close.call(this, initData);
        }
        errorThrown = false;
      } finally {
        if (errorThrown) {
          try {
            this.closeAll(i + 1);
          } catch (e) {}
        }
      }
    }
    this.wrapperInitData.length = 0;
  }
};

module.exports = TransactionImpl;
複製程式碼

Transaction的主要作用就是包裝一個函式,函式的執行交給Transaction,同時Transaction會在函式執行前後執行被注入的Wrappers,一個Wrapper有二個方法initializecloseWrapper是通過getTransactionWrappers方法注入的

程式碼很簡單,很容易看明白我就具體說明下每個函式和關鍵屬性的作用

  1. perform執行注入的函式fnwrappers,執行順序為initializeAll--> fn -->closeAll
  2. initializeAll執行所有Wrapperinitialize方法
  3. closeAll執行所有Wrapperclose方法
  4. reinitializeTransaction初始化
  5. isInTransaction 判斷事務是否在執行

瞭解了Transaction我們再來仔細分析下上面的程式碼

var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(
    /* useCreateElement */
    !shouldReuseMarkup &&
        ReactDOMFeatureFlags.useCreateElement
);
複製程式碼

ReactReconcileTransactiontransition做了一成包裝

ReactReconcileTransaction

 var TRANSACTION_WRAPPERS = [
    SELECTION_RESTORATION,
    EVENT_SUPPRESSION,
    ON_DOM_READY_QUEUEING
];

if ("development" !== "production") {
    TRANSACTION_WRAPPERS.push({
        initialize:
            ReactInstrumentation.debugTool.onBeginFlush,
        close: ReactInstrumentation.debugTool.onEndFlush
    });
}

function ReactReconcileTransaction(useCreateElement) {
    this.reinitializeTransaction();
    this.renderToStaticMarkup = false;
    this.reactMountReady = CallbackQueue.getPooled(
        null
    );
    this.useCreateElement = useCreateElement;
}
var Mixin = {
    getTransactionWrappers: function() {
        return TRANSACTION_WRAPPERS;
    },
    getReactMountReady: function() {
        return this.reactMountReady;
    },
    getUpdateQueue: function() {
        return ReactUpdateQueue;
    },
    checkpoint: function() {
        // reactMountReady is the our only stateful wrapper
        return this.reactMountReady.checkpoint();
    },
    rollback: function(checkpoint) {
        this.reactMountReady.rollback(checkpoint);
    },
    destructor: function() {
        CallbackQueue.release(this.reactMountReady);
        this.reactMountReady = null;
    }
};
複製程式碼

getTransactionWrappers方法裡面返回的是TRANSACTION_WRAPPERS他的值有4個也就是說注入了四個Wrapper。具體看看ON_DOM_READY_QUEUEING這個Wraper;

 var ON_DOM_READY_QUEUEING = {
    /**
     * Initializes the internal `onDOMReady` queue.
     */
    initialize: function() {
        this.reactMountReady.reset();
    },

    /**
     * After DOM is flushed, invoke all registered `onDOMReady` callbacks.
     */
    close: function() {
        this.reactMountReady.notifyAll();
    }
};
複製程式碼

this.reactMountReady是一個佇列, 在元件構建真實dom之後

transaction
    .getReactMountReady()
    .enqueue(function() {
        measureLifeCyclePerf(
            function() {
                return inst.componentDidMount();
            },
            _this._debugID,
            "componentDidMount"
        );
    });
複製程式碼

會將componentDidMount方法push進入佇列裡面. 而mountComponentIntoNode(插入到了document中了)執行完畢之後會執行ON_DOM_READY_QUEUEING.close方法也就是this.reactMountReady.notifyAll()方法,釋放佇列中所有的元素。

componentDidMount是通過一個佇列來維護的,因為佇列是先進先出的.而最裡層的元件是最新執行!

元件的更新this.setState

先看看下面二段程式碼, console.log(this.props.name, this.state.k)輸入結果是什麼?會輸出二次嗎?為什麼?

class Child extends React.Component {
    state = {
        k:null
    }
    render(){
        console.log(this.props.name, this.state.k) 
        return (<div onClick={() => {
            this.setState({ k:12})             // (1)
            this.props.onChange("leiwuyier");  // (2)
        }}>
            child
        </div>)
    }
}
class App extends React.Component {
    state = {
        name:"leiwuyi"
    }
    render(){
        return (
            <div>
                <Child name={this.state.name} onChange={(name) => {
                    this.setState({
                        name
                    })
                }}></Child>
            </div>
        )
    }
}
複製程式碼

如果把(1)(2)調換位置呢?輸出的結果又什麼怎麼樣的呢? 答案就是隻會輸出一次"leiwuyi",12.

  1. 因為setState()是非同步的,所以(1)(2)調換位置沒什麼區別.
  2. 只更新一次原因是App先更新,更新的過程中會將Child例項(指的是instance)屬性的updateBatchNumber設定為null所以Child元件不會獨自更新一次;

帶著這二個問題來看this.setState()的程式碼

ReactComponent.prototype.setState = function(partialState,callback) {
    ...
    ...
    this.updater.enqueueSetState(this, partialState);
                       
};
複製程式碼

this.updater是在例項的時候被賦值的.

 function ReactComponent(props, context, updater) {
    this.props = props;
    this.context = context;
    this.refs = emptyObject;
    // We initialize the default updater but the real one gets injected by the
    // renderer.
    this.updater = updater || ReactNoopUpdateQueue;
}
複製程式碼

上一章說過. 例項是執行在ReactCompositeComponent.mountComponent

var updateQueue = transaction.getUpdateQueue();
    // Initialize the public class
    var doConstruct = shouldConstruct(Component);
    var inst = this._constructComponent(
        doConstruct,
        publicProps,
        publicContext,
        updateQueue
    );
複製程式碼

最終追蹤到getUpdateQueue方法是在ReactUpdateQueue類裡面

enqueueSetState: function( publicInstance,partialState ) {
    if ("development" !== "production") {
        ReactInstrumentation.debugTool.onSetState();
        "development" !== "production"
            ? warning(
                  partialState != null,
                  "setState(...): You passed an undefined or null state object; " +
                      "instead, use forceUpdate()."
              )
            : void 0;
    }

    var internalInstance = getInternalInstanceReadyForUpdate(
        publicInstance,
        "setState"
    );

    if (!internalInstance) {
        return;
    }

    var queue =
        internalInstance._pendingStateQueue ||
        (internalInstance._pendingStateQueue = []);
    queue.push(partialState);

    enqueueUpdate(internalInstance);
},

複製程式碼

首先拿到例項internalInstance(上一章說到過的具有mountComponent方法的那個例項) 然後將state存到一個佇列queue裡面. 接下來看看enqueueUpdate方法

var ReactDefaultBatchingStrategy = {
    isBatchingUpdates: false,
    batchedUpdates: function(callback, a, b, c, d, e) {
        var alreadyBatchingUpdates =
            ReactDefaultBatchingStrategy.isBatchingUpdates;
        ReactDefaultBatchingStrategy.isBatchingUpdates = true;
        if (alreadyBatchingUpdates) {
            return callback(a, b, c, d, e);
        } else {
            return transaction.perform();  
        }
    }
};

function enqueueUpdate(component) {
    ensureInjected();
    if (!batchingStrategy.isBatchingUpdates) {  
        batchingStrategy.batchedUpdates(
            enqueueUpdate,
            component
        );
        return;
    }
    dirtyComponents.push(component);
    if (component._updateBatchNumber == null) {
        component._updateBatchNumber =
            updateBatchNumber + 1;
    }
}
複製程式碼

batchingStrategy.isBatchingUpdates是控制元件的更新. 合成事件那塊有時間我會新開一個章詳細講解。

onClick={() => {this.setState({});console.log(1)}}
複製程式碼

點選之後其實會執行batchingStrategy.batchedUpdates()方法,由於isBatchingUpdates為false所以最終執行的是

transaction.perform(() => {this.setState({}));console.log(1)})
複製程式碼

執行之後.isBatchingUpdates被設定為true 前面對事務說的很清楚了.

// 這是注入的二個warpper
var RESET_BATCHED_UPDATES = {
    initialize: emptyFunction,
    close: function() {
        ReactDefaultBatchingStrategy.isBatchingUpdates = false;
    }
};
var FLUSH_BATCHED_UPDATES = {
    initialize: emptyFunction,
    close: ReactUpdates.flushBatchedUpdates.bind(
        ReactUpdates
    )
};
// 所以執行順序是
 FLUSH_BATCHED_UPDATES.initialize()
 RESET_BATCHED_UPDATES.initialize()
 this.setState({});console.log(1);
 FLUSH_BATCHED_UPDATES.close()
 RESET_BATCHED_UPDATES.close()
複製程式碼

isBatchingUpdatestrue了所以this.setState執行的dirtyComponents.push(component),push之後 this.setState({})也就執行完了,然後執行console.log(1);最後通過FLUSH_BATCHED_UPDATES.close更新元件.

在事件函式裡面的this.setState()的isBatchingUpdates為true,所以只會放入dirtyComponents,函式執行完畢,才會更新元件。這就是解釋了this.setState為什麼是非同步的原因

updateComponent

// 有了dirtyComponents之後
for (var i = 0; i < len; i++) {
    var component = dirtyComponents[i];
    ReactReconciler.performUpdateIfNecessary(
        component,
        transaction.reconcileTransaction,
        updateBatchNumber
    );
    ==>
    performUpdateIfNecessary: function(internalInstance, transaction, updateBatchNumber) {
        // 作了一層判斷,為什麼Child不會獨自更新一次,原因就在這裡
        if ( internalInstance._updateBatchNumber !== updateBatchNumber) {
            return;
        }
        internalInstance.performUpdateIfNecessary(
            transaction
        );
    }
    ==> 
    updateComponent(){
        // 執行componentWillReceiveProps方法
        if (
            willReceive &&
            inst.componentWillReceiveProps
        ) {
            if ("development" !== "production") {
                measureLifeCyclePerf(
                    function() {
                        return inst.componentWillReceiveProps(
                            nextProps,
                            nextContext
                        );
                    },
                    this._debugID,
                    "componentWillReceiveProps"
                );
            } else {
                inst.componentWillReceiveProps(
                    nextProps,
                    nextContext
                );
            }
        }
        
        // 合併state
        var nextState = this._processPendingState(
            nextProps,
            nextContext
        );
        
        // 執行shouldComponentUpdate
        var shouldUpdate = true;
        if (!this._pendingForceUpdate) {
            if (inst.shouldComponentUpdate) {
                if ("development" !== "production") {
                    shouldUpdate = measureLifeCyclePerf(
                        function() {
                            return inst.shouldComponentUpdate(
                                nextProps,
                                nextState,
                                nextContext
                            );
                        },
                        this._debugID,
                        "shouldComponentUpdate"
                    );
                } else {
                    shouldUpdate = inst.shouldComponentUpdate(
                        nextProps,
                        nextState,
                        nextContext
                    );
                }
            } 
            ..
        }   
        // 更新元件
        if (shouldUpdate) {
            this._performComponentUpdate(
                nextParentElement,
                nextProps,
                nextState,
                nextContext,
                transaction,
                nextUnmaskedContext
            );
        }
    }
}
複製程式碼

注意合併state是在什麼時候,是在componentWillReceiveProps之後shouldComponentUpdate之前進行的. 合併state之後是不能再進行setState()操作的.因為合併之的後_pendingStateQueuenull,再這之後使用setState()會將_pendingStateQueue設定為true_pendingStateQueuetrue就會又一次執行updateComponent無限迴圈下去, 這解釋了shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate裡面不能做this.setState操作.

那為什麼在componentWillReceiveProps裡面可以進行setState()操作componentWillReceiveProps的時候不也是為true嗎?因為componentWillReceiveProps有做

// 元件內部的this.setState,prevParentElement與nextParentElement是相等的. 所以willReceive為false不會再迴圈執行componentWillReceiveProps了
if (prevParentElement !== nextParentElement) {
    willReceive = true;
}

複製程式碼

流程圖如下

React原始碼解析(3):元件的生命週期

處理了componentWillReceivePropsshouldComponentUpdate這二個生命週期之後然後對元件進行更新this._performComponentUpdate

this._performComponentUpdate

if (inst.componentWillUpdate) {
        if ("development" !== "production") {
            measureLifeCyclePerf(
                function() {
                    return inst.componentWillUpdate(
                        nextProps,
                        nextState,
                        nextContext
                    );
                },
                this._debugID,
                "componentWillUpdate"
            );
        } else {
            inst.componentWillUpdate(
                nextProps,
                nextState,
                nextContext
            );
        }
    }
this._updateRenderedComponent(
    transaction,
    unmaskedContext
);

if (hasComponentDidUpdate) {
    if ("development" !== "production") {
        transaction
            .getReactMountReady()
            .enqueue(function() {
                measureLifeCyclePerf(
                    inst.componentDidUpdate.bind(
                        inst,
                        prevProps,
                        prevState,
                        prevContext
                    ),
                    _this2._debugID,
                    "componentDidUpdate"
                );
            });
    } else {
        transaction
            .getReactMountReady()
            .enqueue(
                inst.componentDidUpdate.bind(
                    inst,
                    prevProps,
                    prevState,
                    prevContext
                ),
                inst
            );
    }
}

複製程式碼

是不是感到非常眼熟,跟元件的掛載非常類似, 先執行componentWillUpdate方法然後通過_updateRenderedComponent遞迴的更新元件,更新完成之後執行transaction裡面的Wrapper中的close方法, close將釋放componentDidUpdate的佇列.

說到這裡,元件的生命週期也就是講完了. 還有三個比較核心的點.

  1. diff演算法 (同級之間的比較,更新前後的虛擬dom到底是如何對比的)
  2. 事件系統, (React合成系統到底是什麼?)
  3. fiber架構 (React16版本革命性的變革)

相關文章