一个项目只有一给仓库,状态也只能有一个,但是组件会非常之多,我们为了每个组件的共享状态便于统一管理,需要将多个reducer进行合并
export default function combineReducers(reducers) {
const reducerKeys = Object.keys(reducers);// [counter1,counter2]
return function (state = {}, action) {
const nextState = {};
let hasChanged = false;
for (let index = 0; index < reducerKeys.length; index++) {
const key = reducerKeys[index]; // counter1
const previousStateForKey = state[key];//{number:0}
const reducer = reducers[key];//counter1
const nextStateForKey = reducer(previousStateForKey, action)// {number:0}
nextState[key] = nextStateForKey
hasChanged = hasChanged || nextStateForKey !== previousStateForKey
}
console.log('nextState', nextState)// {counter1:{number:0},counter2:{number:0}}
return hasChanged ? nextState : state;
}
}