我正在使用 React 挂钩useReducer
来管理类似购物车的应用程序的状态。我cartReducer
习惯于处理添加/删除/更改项目数量:
// utils/reducers.js
export const cartReducer = (state, action) => {
switch (action.type) {
case ACTIONS_TYPES.ADD_ITEM: {
// ...
}
case ACTIONS_TYPES.REMOVE_ITEM: {
// ...
case ACTIONS_TYPES.EMPTY_CART: {
// ...
}
case ACTIONS_TYPES.CHANGE_ITEM_QTY: {
// ...
}
default: {
throw new Error('Unrecognized action in cartReducer.');
}
}
};
cartReducer
在我的购物车组件中使用了减速器:
const [cart, dispatch] = useReducer(cartReducer, { items: [] });
现在,我想使用我喜欢的库添加通知,但我不知道如何处理它。我想我有3个选择:
- 选项1:污染我调用库的reducer,即
showSuccessToast()
在返回新状态之前添加类似的函数; - 选项 2:创建新的操作,例如
ACTIONS_TYPES.SHOW_SUCCESS_TOAST
,但这需要我更改所有dispatch()
调用; - 选项3:创建一个新的
cartNotificationReducer
添加功能,如showSuccessToast()
我知道某些选项可能是反模式,所以我认为选项 3 是最好的。但是useReducer
只接受一个减速器......我该如何组合它们?