• 手写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
        }
    } 
  • 相关阅读:
    oracle比较常用的函数
    生成GUID
    字符串操作
    Visual Studio常用快捷键
    c#保存异常日志
    c#的Trim方法
    c#之文件操作
    Python可视化库matplotlib.pyplot里contour与contourf的区别
    python linspace
    神经网络实现连续型变量的回归预测(python)
  • 原文地址:https://www.cnblogs.com/qydknowledge/p/14235992.html
Copyright © 2020-2023  润新知