javascript - 避免重复州名

标签 javascript reactjs ecmascript-6 redux

假设我有一个如下所示的 rootreducer

const rootR = combineReducers({
  topics,
  ...
});

主题 reducer

function topics(state = { topics=[], error: null}, action){
  switch (action.type){
    case types.FETCH_TOPICS_SUCCESSFULLY:
      const { topics } = action;
      return {
        ...state,
        topics,
      };
    default:
      return state;
  }
};

当我触发相关操作时,我得到具有可重复属性的状态 state.topics.topics 而不是 state.topics

有什么办法可以避免这种重复(topics.topics)?

提前致谢

最佳答案

查看 topics reducer 的 initialState,topics reducer 可访问的状态对象具有以下结构:

{
    topics: [],
    error: null
}

所以当您像这样组合Reducers时:

const rootR = combineReducers({
  topics,
  anotherReducer,
  someOtherReducer.
  // ...
});

生成的全局应用状态将如下所示:

{
    topics: {
        topics: [],
        error: null
    },
    anotherReducer: {
        // ...
    },
    someOtherReducer: {
        // ...
    },

    // ...        
}

所以如果你想从全局状态访问topics数组,你需要做state.topics.topics

state.topics 下有两个东西,topics 数组和error。 因此,让我们将第二个 topics 键重命名为 items 以避免混淆。 (难免要有第二个key来存放数组,因为你也想要error)

因此我们有:

state.topics = {
    items: [],
    error: null,
}

现在我们访问 state.topics.items 而不是 state.topics.topics

为实现这一点,传递给 topics reducer 的 initialstate 必须是:

function topics(state = { items = [], error: null }, action){
    //...
}

现在在 reducer FETCH_TOPICS_SUCCESSFULLY 中,我们想要将数组 action.topics 附加到 items,就像这样(不改变我们的当前状态):

case types.FETCH_TOPICS_SUCCESSFULLY:
    const { topics } = action;
    return {
        ...state,
        items: [
            ...state.items,
            ...topics
        ],
    };

关于javascript - 避免重复州名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40851685/

相关文章:

javascript - 编辑输入类型时如何更改值属性?

reactjs - 通过变量动态导入文件 - React Native

javascript - 对象方法无法访问 ES6 JavaScript 对象的计算属性

javascript - 如何忽略 TS 错误 TS2339 : “property does not exist on value of type” with eslint

javascript - Moment js按周和星期几获取一个月的特定日期

javascript - 创建一个同时服务于经典 ASP 和 ASP.Net 的类

reactjs - 在 React 应用程序 Pod 中无法访问 kubectl secret

reactjs - 使用 ImmutableJS 对象作为 React 组件状态

Javascript,ES5+还有激活对象吗?

javascript - 一个表单和两个提交按钮事件处理程序使控制台闪烁