使用redux,我有一堆动作和一堆与每个动作类型一致的缩减器。
每个动作都映射到正在更新的状态的不同部分(所有动作创建者主要用于从API获取数据,例如,映射到状态的某个部分)。我们的减速器目前看起来相当愚蠢(简化为A,B,C,为了示例):
export const rootReducer = combineReducers({
somePartOfStateA: someAReducer,
somePartOfStateB: someBReducer,
somePartOfStateC: someCReducer,
... (and many other reducers)
});
function someAReducer(state = [], action) {
switch (action.type) {
case FETCH_SOME_A:
return action.payload;
default:
return state;
}
}
function someBReducer(state = [], action) {
switch (action.type) {
case FETCH_SOME_B:
return action.payload;
default:
return state;
}
}
function someCReducer(state = [], action) {
switch (action.type) {
case FETCH_SOME_C:
return action.payload;
default:
return state;
}
}
// and a bunch of pretty much identical reducers continue below
根据我的理解,将它们拆分的目的是使每个reducer处理状态命名空间的一部分。由此产生的减速器很简单,但反复几乎相同。有没有推荐的方法来巩固每个州的所有这些减速器?
答案 0 :(得分:3)
Reducer只是一个功能。您可以使用更高阶的功能为您制作减速器。
const makeSingleActionReducer = type => (state, action) =>
action.type === type ? action.payload : state
export const rootReducer = combineReducers({
somePartOfStateA: makeSingleActionReducer(FETCH_SOME_B)
...
})
您还可以通过创建配置{stateKey: actionType, ...}
并循环遍历它来进一步发展。