react中createStore, conbineRdeducers的简易封装

const createStore = (reducer)=>{
        let state = {};//默认的state对象
        let lists = [];//存贮订阅事件
        let actiontypes = "@@init" //默认的type
        let initaction = {
            type :actiontypes //默认的action
        }

        const dispatch = (action = initaction)=>{
            state = reducer(state,action)//将action给了store,store给了reducer 最后reducer修改数据返回state
            lists.map(cb=>{
                cb();//通知组件更新
            })
        }

        const getState = ()=>state //将state return出去

        const subscribe = (cb)=>{
            lists.push(cb)//订阅事件(数据更新)
        }

        dispatch();//初始化


        return {
            dispatch,
            getState,
            subscribe
        }

    }

    const conbineRdeducers = (reducers)=>{
        const newState = {};
        //{tab:{},num:{}}
        return function (state,action) { //reducers为一个函数 所以要ruturn出去一个函数
            for(let key in reducers){//通过遍历将key值放入newState中
                newState[key] = reducers[key](state[key],action)
            }
            return newState
        }
    }

    export {
        createStore,
        conbineRdeducers
    }

 

上一篇:Linux C编程之十九(2) libevent


下一篇:Node.js升级或降低版本