• 手写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
        }
    } 
  • 相关阅读:
    C++模板元编程(二)
    C++模板元编程(一)
    interpret_cast
    Bresenham算法
    Windows中编译Lua源码
    MathJax基础教程与快速参考
    散列表
    Bash脚本实例
    Bash基础
    【iOS】重读《精通Objective-C》(一)
  • 原文地址:https://www.cnblogs.com/qydknowledge/p/14235992.html
Copyright © 2020-2023  润新知