【发布时间】:2019-05-05 18:42:22
【问题描述】:
我有一家形状像这样的商店:
{
// ...data
user: {
warranties: {
W_1: ['O_1', 'O_2'],
W_2: ['O_3', 'O_4']
}
}
}
以W_ 开头的键是保修,以O_ 开头的键是选项。
对于每个保修,我都有一个或多个与之关联的选项,user.warranties 中的关系采用以下形式:warranty => [options]。
为了实现它,我正在像这样组合我的减速器:
rootReducer = combineReducers({
// ...other main reducers
user: combineReducers({
// ...other user reducers
warranties
})
})
现在,“问题”是USER_WARRANTY 和USER_OPTION 操作都由同一个reducer 处理,因为:
当我添加一个选项时,我需要将它推送到正确的保修条目。
相反,当我添加保修时,我需要使用其默认选项填充它。
最终,它们对同一数据片进行操作
所以warranties 减速器必须对这两个动作做出反应,如下所示:
export default function warranties(state = {}, action) {
switch (action.type) {
case USER_WARRANTIES_ADD:
// add warranty key to `user.warranties`
case USER_WARRANTIES_REMOVE:
// remove warranty key from `user.warranties`
case USER_OPTIONS_ADD:
// push option to `user.warranties[warrantyID]`
case USER_OPTIONS_REMOVE:
// remove option from `user.warranties[warrantyID]`
default:
return state
}
}
我想将其拆分为两个 reducer,warranties 和 options,但仍让它们对同一数据片进行操作。
理想情况下,我会像这样组成我的根减速器:
rootReducer = combineReducers({
// ...other main reducers
user: combineReducers({
// ...other user reducers
warranties: magicalCombine({
warranties,
options
})
})
})
magicalCombine 是我很难找到的函数。
我已经尝试过reduce-reducers,但看起来第二个减速器 (options) 从未真正到达过,而且我实际上不确定它,因为我不是试图实现平坦状态,而是实际上在相同的键。
【问题讨论】:
标签: redux store redux-thunk reducers redux-store