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 }
标签:const,cb,react,state,let,key,action,createStore,conbineRdeducers 来源: https://www.cnblogs.com/wildccy/p/10702979.html