在React-redux中,使用switch case语句是常见的处理reducer的方法。然而,如果你不想使用switch case,你可以使用一个对象来存储reducer的处理函数,并根据action类型来调用相应的处理函数。
以下是一个示例代码:
// 定义reducer的处理函数
const initialState = {
count: 0
};
const incrementCount = (state, action) => {
return {
...state,
count: state.count + 1
};
};
const decrementCount = (state, action) => {
return {
...state,
count: state.count - 1
};
};
// 创建reducer对象
const reducer = {
INCREMENT: incrementCount,
DECREMENT: decrementCount
};
// 定义root reducer
const rootReducer = (state = initialState, action) => {
// 查找并调用相应的处理函数
const handler = reducer[action.type];
if (handler) {
return handler(state, action);
}
return state;
};
export default rootReducer;
在上面的代码中,我们定义了一个包含两个处理函数的reducer对象,并使用action的类型来查找并调用相应的处理函数。如果找不到相应的处理函数,则返回原始的state。
这种方法的好处是,可以将reducer的逻辑分离到不同的函数中,使代码更加清晰和易于维护。