本文主要是介绍Redux中reducer的二级拆分,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
javascript 代码
'use strict';
const Redux = require('redux');
const createStore = Redux.createStore;
const combineReducers = Redux.combineReducers;/*reducers为一个对象,键值与store中state的键值相对应*/
/*合并reducers的内部简要处理逻辑*/
function combineRecucers(reducers) {return function(state, action) {/*返回一个全新的state*/let newState = {};/*进行处理*/for (let key in reducers) {newState[key] = reducers[key](state[key], action)}return newState;}
}function aReducer(state = [], action) {console.log('a');switch(action.type) {case 'a': /*应该返回一个全新的state*/return state.concat([action.data]);default: return state;}
}function bReducer(state = [], action) {console.log('b');switch(action.type) {case 'b': return state.concat([action.data]);default: return state;}
}function cReducer(state = {name: '', group: []}, action) {console.log('c');switch(action.type) {case 'c': /*return {name: cNameReducer(undefined, action),group: cGroupReducer(undefined, action)};*//*对子state进一步进行reducer的拆分合并*/return combineReducers({name: cNameReducer, group: cGroupReducer})(state, action);default: return state;}
}function cNameReducer(state, action) {console.log('c1');if (state === undefined) return '';if (action.type === 'c') {return action.name;} else {return state;}
}function cGroupReducer(state, action) {console.log('c2');if (state === undefined) return [];if (action.type === 'c') {return state.concat([action.item]);} else {return state;}
}/*多个reducer需要与state结构相对应*/
const reducers = {a: aReducer, //会将store中state中的键值 'a' 对应的值传给函数 aReducer的第一个参数b: bReducer, //会将store中state中的键值 'b' 对应的值传给函数 bReducer的第一个参数c: cReducer
};/*合并多个reducer为一个reducer*/
const reducer = combineReducers(reducers);/*第二个参数为初始化store的state*/
const store = createStore(reducer, {a: [111],b: [222],c: {name: '',group: []}
});/*一旦dispatch被触发,subscribe中注册的监听器也会触发*/
store.subscribe(() => {console.log(store.getState()); //获取store中的最新state
})let action = {type: 'a',data: 'exwe'
};let action2 = {type: 'c',name: 'roaming',item: 'code'
};/*每一个dispatch都会将所有的reducer执行一遍*/
store.dispatch(action);
store.dispatch(action2);
这篇关于Redux中reducer的二级拆分的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!