Redux源码解读

79 阅读1分钟

Redux源码解读

import _ from '@/assets/utils';



export const createStore = function createStore(reducer) {

    let state,

        listeners = [];



    // 获取状态

    const getState = function getState() {

        return _.clone(true, state);

    };



    // 事件池管理

    const subscribe = function subscribe(listener) {

        if (typeof listener !== 'function') {

            throw new Error(`Expected the listener to be a function.`);

        }

        if (listeners.some(item => item === listener)) return;

        listeners.push(listener);



        return () => {

            listeners.filter(item => item !== listener);

        };

    };



    // 任务派发

    const dispatch = function disptach(action) {

        if (!_.isPlainObject(action)) {

            throw new Error("Actions must be plain objects.");

        }

        if (typeof action.type === 'undefined') {

            throw new Error('Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');

        }

        // 修改状态

        try {

            state = reducer(state, action);

        } catch (_) { }



        // 通知事件池中的方法执行

        listeners.forEach(listener => {

            if (typeof listener === "function") {

                listener()

            }

        });



        return action;

    };



    // 默认派发执行一次:设置状态初始值

    const randomString = function randomString() {

        return Math.random().toString(36).substring(7).split('').join('.');

    };

    dispatch({

        type: `@@redux/INIT${randomString()}`

    });



    return {

        getState,

        subscribe,

        dispatch

    };

};