简体   繁体   English

如何组织嵌套的Redux减速器?

[英]How to organize a nested Redux reducer?

My reducer for a section of my application is going to be deeply nested 我的应用程序的某个部分的减速器将被深深嵌套

 export const MainReducers = function(state = mapDataToInitialState(), 
 action = {}) {
   switch (action.type) {
               case Constants.SET_FOO:
        return update(state, {

          sheet: {
            stream: {
              appeal_0: {
                issues: {
                  problem1: {
                    foo: {
                      $set: action.payload.foo
                    }
                  }
                }
              }
            }
          }
        });

        case Constants.SET_BAR:
        return update(state, {
          // TODO make reusable for all issues fields
         sheet: {
            stream: {
              person: {
                issues: {
                  problem1: {
                    bar: {
                      $set: action.payload.bar
                    }
                  }
                }
              }
            }
          }
        });
   default: return state;
  }
 };

And I have many of these to add, How can i abstract the nesting of the object in a better way 我要添加许多这样的内容,如何更好地抽象对象的嵌套

I was thinking something like return newState type of thing. 我在想类似return newState类型的东西。 I don't really understand if combine reducer is for this type of thing. 我真的不知道是否组合减速器用于这种类型的事情。 The redux documentation is hard for me to understand thus i need a better example of how to organize the reducer.. thanks Redux文档让我很难理解,因此我需要一个更好的示例来说明如何组织化简。

combineReducers is definitely the way to go. CombineReducers绝对是必经之路。 You may also have some success normalising and flattening your state so that it's easier to work with. 您也可以在正常化和展平状态方面取得一些成功,以便更轻松地使用它。

So you might want to do 所以你可能想做

const appReducer = combineReducers({
    streams: streamReducer,
    people: peopleReducer,
    issues: issueReducer
});

Then your components can grab the individual bits they want in mapStateToProps, rather than getting a huge great big object: 然后,您的组件可以在mapStateToProps中获取所需的单个位,而不用获取巨大的大型对象:

function mapStateToProps( state, ownProps ) {
    return {
        person: state.people[ ownProps.personId ]
        issues: state.issues[ ownProps.personId ]
    };
}

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

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