【问题标题】:How to organize a nested Redux reducer?如何组织一个嵌套的 Redux reducer?
【发布时间】:2018-02-15 10:52:51
【问题描述】:

我的应用程序部分的 reducer 将被深度嵌套

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

我还有很多要补充的,我怎样才能以更好的方式抽象对象的嵌套

我在想return newState 之类的东西。我真的不明白组合减速器是否适用于这种类型的东西。 redux 文档对我来说很难理解,因此我需要一个更好的例子来说明如何组织 reducer.. 谢谢

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux reducers


    【解决方案1】:

    combineReducers 绝对是要走的路。您还可以成功地规范化和扁平化您的状态,使其更易于使用。

    所以你可能想这样做

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

    然后您的组件可以在 mapStateToProps 中获取他们想要的各个位,而不是获取一个巨大的大对象:

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

    【讨论】:

    • 这并不能解决嵌套问题。数据已经扁平化了。我在更新数据方面没有太多选择。但我不想重复深层嵌套
    • 哦,我明白了 - 我需要一个问题减少器
    • 在我的情况下它并没有真正起作用,但这似乎是正确的答案
    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2017-09-03
    • 2018-06-03
    • 2020-12-05
    相关资源
    最近更新 更多