2

我有一个形状像这样的商店:

{
  // ...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处理,因为:

  • 添加选项时,我需要将其推送到正确的保修条目。

  • 相反,当我添加保修时,我需要使用其默认选项填充它。

  • 最终,它们对同一片数据进行操作

因此,warrantiesreducer 必须对这两个动作做出反应,如下所示:

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

我想把它分成两个减速器,warrantiesoptions,但仍然让它们在同一个数据片上运行。

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

rootReducer = combineReducers({
  // ...other main reducers

  user: combineReducers({
    // ...other user reducers
    warranties: magicalCombine({
      warranties,
      options
    })
  })
})

magicalCombine我很难找到的功能在哪里。


我试过reduce-reducers了,但看起来第二个减速器(options)实际上从未到达过,而且我实际上不确定它,因为我不是试图达到平坦状态,而是实际上在同一个键上操作。

4

1 回答 1

2

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

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

于 2018-12-05T13:39:37.413 回答