有没有一种方法来构造const reducer = (state = initialState, action),使得该方法不会因大量开关盒而肿?

我的想法是将相关动作放入数组中,并在处理动作时使用Array.prototype.includes()进行检查。

然后,我将提取与新方法中的特定操作相关的切换案例(例如,List组件将具有LIST_ADDLIST_REMOVE等),并调用这些方法,而不是仅在方法。

这会提高性能,但至少是结构化的。

还有更好的主意吗?

最佳答案

官方Redux docs提供了这个非常方便的reducer创建者:

function createReducer(initialState, handlers) {
  return function reducer(state = initialState, action) {
    if (handlers.hasOwnProperty(action.type)) {
      return handlers[action.type](state, action)
    } else {
      return state
    }
  }
}

这使您可以按如下方式创建减速器:
const reducer = createReducer(initialState, {
  [actionType.ACTION1]: specificActionReducer1,
  [actionType.ACTION2]: specificActionReducer2,
}

没有switch语句!

08-15 18:28