我想合并两个化简器,第一个化简器是作为通用化简器创建的,第二个化简器是针对其自身状态的。这两个减速器将无法处理相同的情况。这将有所帮助,因为我只对通用类进行一次测试。
如果您在考虑reduceReducers
或combineReducers
,这似乎不起作用,因为我有很多“特殊”减速器,每个减速器都具有相同的操作类型来处理,所有这些异径管有不同的状态部分可以修改。
const initialState = {
byId : {},
ids: []
}
const dogsReducer = ({ dogs: state = initialState, ...restOfState }, action) => {
switch (action.type) {
case INITIALIZE:
return {
byId : _.keyBy(state.dogs, 'id'),
ids: state.map(({id}) => id)
}
case RESET:
return initialState
case SPECIFIC_DOG_ACTION:
...
default:
return state
}
}
const catsReducer = ({ cats: state = initialState, ...restOfState}, action) => {
switch (action.type) {
case INITIALIZE:
return {
byId : _.keyBy(state, 'id'),
ids: state.map(({id}) => id)
}
case RESET:
return initialState
case SPECIFIC_CAT_ACTION:
...
default:
return state
}
}
我想在通用的switch / case函数或通用的reducer中隔离以下情况:INITIALIZE
和RESET
,所以我只需要测试一次这些情况,而不必在每个reducer中进行测试。将来会有更多的通用案例,这就是为什么我要避免重复。
这是预期的结果:
const genericReducer = (state = initialState, action) => {
switch (action.type) {
case INITIALIZE:
return {
byId : _.keyBy(state.dogs, 'id'),
ids: state.map(({id}) => id)
}
case RESET:
return initialState
default:
return state
}
}
const dogsReducer = ({ dogs: state = initialState, ...restOfState }, action) => {
switch (action.type) {
case SPECIFIC_DOG_ACTION:
...
default:
return state
}
}
const catsReducer = ({ cats: state = initialState, ...restOfState}, action) => {
switch (action.type) {
case SPECIFIC_CAT_ACTION:
...
default:
return state
}
}
const finalCatsReducer = mergeReducers(catsReducer, genericReducer)
const finalDogsReducer = mergeReducers(dogsReducer, genericReducer)
我已经在这里想出了一个简单的解决方案:
const dogsReducer = ({ dogs: state = initialState, ...restOfState }, action) => {
switch (action.type) {
case SPECIFIC_DOG_ACTION:
...
default:
return genericReducer(state, action)
}
}
const catsReducer = ({ cats: state = initialState, ...restOfState}, action) => {
switch (action.type) {
case SPECIFIC_CAT_ACTION:
...
default:
return genericReducer(state, action)
}
}
但是我不满意,因为我更喜欢使用一个函数“注入” reducer(mergeReducers(catsReducer, genericReducer)
)。