手写createStore

export default function createStore(reducer, DefaultState) {

    let currentState = DefaultState,
        currentReducer = reducer
    let listeners = [];

    function isPlainObject() {
        if (typeof reducer === "object") {
            return false;
        }
        return Object.getPrototypeOf(reducer) === Object.prototype
    }

    function dispatch(action) {
        if (!isPlainObject) {
            throw new Error("must be a plain object")
        }
        if (action.type === undefined) {
            throw new Error("must has a property of type")
        }
        currentState = currentReducer(currentState, action);
        for (const listener of listeners) {
            listener();
        }
    }

    function getState() {
        return currentState;
    }
    /**
     * @author qian
     * @name 监听器
     * @param {监听函数} listener 
     */
    function subscribe(listener) {
        listeners.push(listener);
        let isRemove = true;
        return () => {
            if (isRemove) {
                const index = listeners.indexOf(listener);
                listeners.splice(index, 1);
                isRemove = false;
            }
        }
    }

    function replaceReducer(newReducer) {
        currentReducer = newReducer;
    }

    //初建库时需要分发一次action
    dispatch({
        type: "@@redux/INIT" + Math.random().toString().substr(2, 7).split("").join(".")
    })

    return{
        dispatch,
        getState,
        subscribe,
        replaceReducer
    }
} 

 

posted @ 2021-01-05 15:15  漫漫长路上的求知者  阅读(100)  评论(0编辑  收藏  举报