码迷,mamicode.com
首页 > 其他好文 > 详细

react中createStore, conbineRdeducers的简易封装

时间:2019-04-13 22:01:11      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:cti   let   封装   exp   简易   pre   reducer   遍历   sts   

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
    }

 

react中createStore, conbineRdeducers的简易封装

标签:cti   let   封装   exp   简易   pre   reducer   遍历   sts   

原文地址:https://www.cnblogs.com/wildccy/p/10702979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!