版权声明:转载请注明出处 https://blog.csdn.net/qdmoment/article/details/84063477
combineReducers简单封装
const combineReducers = reducers => {
return (state = {}, action) => {
return Object.keys(reducers).reduce(
(nextState, key) => {
nextState[key] = reducers[key](state[key], action);
return nextState;
},
{}
);
};
};
//分步解析
function(reducers){}() //执行输出 传入reducers
function(state, action){}() //执行输出 传入state action
const reducerArr = Object.keys(reducers) //得到reducer数组(key值数组)
reducerArr.reduce(fn,{}) //执行reduce函数
function fn(nextState, key){ //这里的nextState是一个通过参数方式新定义的变量,首次初始化指向reduce的第二个参数{},执行过后返回的值作为第二次fn的入参
nextState[key] = reducers[key](state[key], action);//存储接收action和旧state后生成的新的state
return nextState;
}
使用,分为直接使用和别名使用:
import { combineReducers } from 'redux';
//直接使用
const chatReducer = combineReducers({
chatLog,
statusMessage,
userName
})
//别名使用
const reducer = combineReducers({
a: doSomethingWithA,
b: processB,
c: c
})