【问题标题】:Split reducers operating on the same slice of data in redux拆分 reducer 在 redux 中对同一片数据进行操作
【发布时间】: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_WARRANTYUSER_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,warrantiesoptions,但仍让它们对同一数据片进行操作。

理想情况下,我会像这样组成我的根减速器:

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


    【解决方案1】:

    reducer 是一个简单的函数,它采用 stateaction 并返回一个新的状态对象,所以我认为这可以满足您的需求..

    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)
      })
    })
    

    combineReducers 来自 redux 只是故意限制为仅传递与提供给它的 reducers 对象中的键匹配的 state 属性的值,它在任何其他方面都没有真正的特殊性。在这里查看更多.. https://redux.js.org/recipes/structuringreducers/beyondcombinereducers

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 2016-08-16
      • 2019-09-03
      • 2018-08-12
      • 2023-03-03
      • 2016-05-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      相关资源
      最近更新 更多