我有一家商店,形状如下:
{
// ...data
user: {
warranties: {
W_1: ['O_1', 'O_2'],
W_2: ['O_3', 'O_4']
}
}
}
以 W_
开头的键为保修,以 O_
开头的键为选项。
对于每个保修,我都有一个或多个与其关联的选项,user.warranties
中的关系采用以下形式:保修=> [选项]
。
为了实现它,我将像这样组合我的 reducer :
rootReducer = combineReducers({
// ...other main reducers
user: combineReducers({
// ...other user reducers
warranties
})
})
现在,“问题”是 USER_WARRANTY
和 USER_OPTION
操作由同一个 reducer 处理,因为:
当我添加选项时,我需要将其推送到正确的保修条目。
相反,当我添加保修时,我需要使用默认选项填充它。
最终,它们对同一数据片进行操作
因此,warranties
reducer 必须对这两个操作使用react,如下所示:
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 ,保证
和选项
,但仍然让它们对同一数据片进行操作。
理想情况下,我会像这样编写我的根 reducer :
rootReducer = combineReducers({
// ...other main reducers
user: combineReducers({
// ...other user reducers
warranties: magicalCombine({
warranties,
options
})
})
})
其中 magicalCombine
是我找不到的函数。
我已经尝试过reduce-reducers
,但看起来第二个 reducer (options
)从未真正到达,而且我实际上不确定它,因为我并不是试图实现平坦状态,而是实际上对同一个键进行操作。
最佳答案
reducer 是一个简单的函数,它接受 state
和 action
并返回一个新的状态对象,所以我认为这会做你想要的事情..
rootReducer = combineReducers({
// ...other main reducers
user: combineReducers({
// ...other user reducers
warranties: (state, action) => {
// state is state.user.warranties
// we pass it to each reducer in turn and return the result
state = warranties(state, action);
return options(state, action);
}
})
})
使用reduceReducers应该做同样的事情(我以前没有使用过它,但这就是它的样子..)
rootReducer = combineReducers({
// ...other main reducers
user: combineReducers({
// ...other user reducers
warranties: reduceReducers(warranties, options)
})
})
redux 中的 combineReducers
只是有意限制为仅传递与提供给它的 reducer 对象中的键相匹配的状态属性的值,它在任何其他方面都没有什么特殊之处。在这里查看更多.. https://redux.js.org/recipes/structuringreducers/beyondcombinereducers
关于redux - 在 redux 中对同一个数据片进行操作的拆分 reducer ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53611242/