简体   繁体   English

如何在ngrx存储中使用单个操作更新多个Reducer的状态?

[英]How to update states of multiple reducers with a single action in ngrx store?

I have multiple reducers in my application which are combined in app.reducers.ts. 我的应用程序中有多个reducers,它们组合在app.reducers.ts中。 When my action happens state of one reducer should be update with single value from current state of the other reducer(so unplanned delivery will become scheduled) and then remove that value from state of second reducer. 当我的动作发生时,一个reducer的状态应该从另一个reducer的当前状态更新为单个值(因此计划外交付将被调度),然后从第二个reducer的状态中删除该值。 Here is how I can delete it, but before doing this I need to update other state. 这是我如何删除它,但在此之前我需要更新其他状态。

case UNPLANNED_ACTIONS.REMOVE_UNPLANNED_DELIVERY:
        return Object.assign({}, state, {
            deliveries: state.deliveries.filter(delivery => delivery.deliveryId !== payload.deliveryId)
        });

Calling 2 actions is very bad from application point of view. 从应用程序的角度来看,调用2个动作非常糟糕。 So I need to somehow handle this on the higher level. 所以我需要以某种方式在更高层次上处理这个问题。

Your store can have multiple reducers, with each acting separately on the action. 您的商店可以有多个减速器,每个减速器分别对动作起作用。

For example, you can define them like 例如,您可以将它们定义为

export function reducer(
  state = initialState,
  action: fromMyStoreActions.DeliveryAction
): AppState{

  switch (action.type) {
    case UNPLANNED_ACTIONS.REMOVE_UNPLANNED_DELIVERY:
         return Object.assign({}, state, {
              deliveries: state.deliveries.filter(delivery => delivery.deliveryId !== payload.deliveryId)
         });
    ...
}

// Another Reducer
export function reducer(
      state = initialState,
      action: fromMyStoreActions.DeliveryAction
    ): AppState{

      switch (...)
....

And then pass all the reducers to ngrx in the module like 然后将所有reducers传递给模块中的ngrx

StoreModule.forRoot(reducers)

For a good example, see this repo 举个好例子,看看这个回购

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM