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);