combineReducers

时间:2024-11-19 22:05:01
const reactInit = '@@react/Init'
const combineReducers  = (reducers) => {
const finalReducers = {}
for (let key in reducers) {
const reducer = reducers[key]
if (typeof reducer === 'undefined') {
console.error(`reducer${key}的值是undefined`)
}
if (typeof reducer === 'function') {
finalReducers[key] = reducer
}
}
for (let key in finalReducers) {
const reducer = finalReducers[key]
const state = reducer(undefined, reactInit)
if (typeof state === 'undefined'){
throw new Error(`reducer${key}的返回值为undefined`)
}
}
return (state={}, action) => {
for (let key in finalReducers) {
const reducer = finalReducers[key]
const newState = reducer(state[key], action)
state[key] = newState
}
return state
}
}