简体   繁体   English

将减速器合并为另一个减速器的关键

[英]Merging reducer as a key in another reducer

I have a reducer reducerA that looks like this 我有一个看起来像这样的减速机reducerA

reducerA = {
  A: [],
  B: {},
  C: {},
  D: [],
};

I have another reducer reducerB that looks like this 我有另一个减速器reducerB看起来像这样

reducerB = {
  E: {},
}

What I would like to do is merge reducerB into reducerA and obtain something that would look something like this 我想做的是将reducerB合并到reducerA并获得看起来像这样的东西

reducerA = {
  A: [],
  B: {},
  C: {},
  D: [],
  reducerB: {
    E: {}
  },
};

Where changes to state variables A,B,C and D are triggered in reducerA function and changes in state variable E is still triggered in reducerB function. reducerA函数中触发状态变量A,B,C和D的更改,而在reducerB函数中仍触发状态变量E的更改。

I have already tried using combineReducers . 我已经尝试过使用combineReducers But apparently, it combines reducerA and reducerB as children of a outer reducer. 但是很显然,它结合了reducerAreducerB作为外部reducer的子级。 And that would require me to access the state variable inside reducerA as reducerA.reducerA.A 这将要求我以reducerA身份reducerA.reducerA.A内部的状态变量。

export default {
  reducerA: combinedReducers({reducerA, reducerB})
}

I would like to know if there is a rather clinical solution to the problem. 我想知道是否有一个相当临床的解决方案。 I found quite a few libraries that do solve the problem. 我发现了很多解决问题的库。 But I am still reluctant about them and would like to solve this without them if possible. 但是我仍然对它们不情愿,如果可能的话,我想在没有它们的情况下解决这个问题。

const reducerA = (state, action) => {
  const newState = {}
  switch (action.type) {
    case someaction:
      newState = {
        A: [],
        B: {},
        C: {},
        D: [],
      }
    default:
      newState = {
        ...state
      }
  }
  return {
    ...newState,
    reducerB: reducerB(state, action)
  }
}

This should solve your problem. 这应该可以解决您的问题。 ;D ; d

I think what you ask for is against the redux reducer concept and breaks encapsulation. 我认为您需要的是违背redux reducer的概念并破坏封装。 If you want to create a reducer which relays on state of reducerA and reducerB, you should probably dispatch the actions which are dispatched be reducerA and reducerB respectively and don't rely on other reducers. 如果要创建一个基于化简器A和化简器B状态的化简器,则可能应该分派分别由化简器A和化简器B调度的动作 ,并且不要依赖于其他化简器。

Anyhow, when you are using react-redux, I'd recommend to employ mapDispatchToProps where you can create a mapping of the global state for your component props, eg: 无论如何,当您使用react-redux时,建议您使用mapDispatchToProps ,在其中您可以为组件mapDispatchToProps创建全局状态的映射,例如:

const mapStateToProps = state => {
  return state.reducerA.foo + state.reducerB.bar
}

connect(mapStateToProps)(YourComponent)

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

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