Redux原始碼createStore解讀常用方法

Dick-Chan發表於2020-08-10

Redux原始碼createStore解讀常用方法

傳入引數

  • reducer,reducer行為函式
  • preloadedState,初始化state資料
  • enhancer,使用(中介軟體等),不常用
const store = createStore(reducer, [preloadedState], enhancer);

getState

直接返回當前currentState,獲取state值,@return state(我覺得應該深克隆一個新的物件返回,不然有可能會被外部修改)

function getState() {
    if (isDispatching) {
        throw new Error('....');
    }
    // console.log(currentState);

    return currentState;
}

dispatch派發行為

執行派發行為,就會在內部執行reducer並且執行之前準備釋出的函式listener ,@params action行為,@return action行為

function dispatch(action) {
        if (!isPlainObject(action)) {
            throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
        }

        if (typeof action.type === 'undefined') {
            throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
        }

        if (isDispatching) {
            throw new Error('Reducers may not dispatch actions.');
        }

        try {
            isDispatching = true;
            currentState = currentReducer(currentState, action);
            //執行reducer函式,會在建立的時候dispatch把剛開始的preloadedState傳進來執行
        } finally {
            isDispatching = false;
        }

        var listeners = currentListeners = nextListeners;

        for (var i = 0; i < listeners.length; i++) {
            var listener = listeners[i];
            listener();//釋出訂閱
        }

        return action;
    }

subscribe函式

redux釋出訂閱

  • 傳入引數時@params function
  • 並用閉包儲存資料,最後可以刪除,@return function unsubscribe
function subscribe(listener) {
        if (typeof listener !== 'function') {//判斷s listener是否函式
            throw new Error('Expected the listener to be a function.');
        }

        if (isDispatching) {//判斷是否派發
            throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribelistener for more details.');
        }

        var isSubscribed = true;
        ensureCanMutateNextListeners();
        nextListeners.push(listener);//把函式壓入棧
        return function unsubscribe() {
            if (!isSubscribed) {
                return;
            }

            if (isDispatching) {
                throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribelistener for more details.');
            }

            isSubscribed = false;
            ensureCanMutateNextListeners();
            var index = nextListeners.indexOf(listener);
            nextListeners.splice(index, 1);
            //刪除陣列裡面的函式,如果連續刪除容易造成陣列塌陷
            currentListeners = null;
        };
    }

如果有錯,望大佬指出。。。

相關文章