# all files / src/ Component.js

21.43% Statements 6/28
0% Branches 0/10
33.33% Functions 1/3
21.43% Lines 6/28

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88

    1×
    1×
    1×
    1×

    1×

    1×

     import {
        transaction
    } from './transaction'

    import {
        extend,
        noop,
        isFn,
        options
    } from './util'

    /**
     *
     *
     * @param {any} props
     * @param {any} context
     */

    export function Component(props, context) {
        this.context = context
        this.props = props
        this.refs = {}
        this._pendingStateQueue = []
        //  if (!this.state)
        this.state = {}
    }

    Component.prototype = {

        setState(state, cb) {
            this._pendingStateQueue.push(state)

            setStateProxy(this, cb)
        },

        forceUpdate(cb) {
            this._pendingForceUpdate = true
            setStateProxy(this, cb)
        },
        _processPendingState: function (props, context) {
            var n = this._pendingStateQueue.length
            if (n == 0) {
                return this.state
            }
            var queue = this._pendingStateQueue.concat()
            this._pendingStateQueue.length = 0

            var nextState = extend({}, this.state);
            for (var i = 0; i < n; i++) {
                var partial = queue[i]
                extend(nextState, isFn(partial) ?
                    partial.call(this, nextState, props, context) :
                    partial)
            }

            return nextState
        },

        render() {}

    }

    /**
     * 让外面的setState与forceUpdate都共用同一通道
     *
     * @param {any} instance
     * @param {any} state
     * @param {any} cb fire by component did update
     * @param {any} force ignore shouldComponentUpdate
     */

    function setStateProxy(instance, cb) {
        if (isFn(cb))
            transaction.queueCallback({ //确保回调先进入
                component: instance,
                cb: cb
            })
        if (!instance._updateBatchNumber) {
            instance._updateBatchNumber = options.updateBatchNumber + 1
        }
        transaction.queueComponent(instance)

        if (!transaction.isInTransation) {
            options.updateBatchNumber++;
            transaction.dequeue()
        }

    }