【问题标题】:Which reducer gets used when using dispatch in mapDispatchToProps? [duplicate]在 mapDispatchToProps 中使用 dispatch 时使用哪个 reducer? [复制]
【发布时间】:2020-09-21 09:01:08
【问题描述】:

我正在学习 Redux,我有两个 reducer,一个用来在页面上显示联系人的 contactReducer 和一个用来乱搞的 testReducer。在我的一个组件文件中,我有这个功能:

const mapDispatchToProps = (dispatch) => ({
  getContacts: () => dispatch({ type: "TEST_ACTION" }),
});

这是我的两个 reducer 文件: 联系减速机:

import { GET_CONTACTS } from "../actions/types";

const initialState = {
  contacts: [
    {
      id: 1,
      name: "John Doe",
      email: "john@gmail.com",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "Karen Williams",
      email: "karen@gmail.com",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "Henry Johnson",
      email: "henry@gmail.com",
      phone: "333-333-333",
    },
  ],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_CONTACTS:
      return {
        ...state,
      };
    default:
      console.log("testing action in contactReducer");
      return state;
  }
}

和 testReducer:

import { GET_CONTACTS } from "../actions/types";

const initialState = {
  contactsTest: [
    {
      id: 1,
      name: "ffffffffffff",
      email: "john@gmail.com",
      phone: "555-555-5555",
    },
    {
      id: 2,
      name: "ggggggggggggg",
      email: "karen@gmail.com",
      phone: "444-444-4444",
    },
    {
      id: 3,
      name: "aaaaaaaaaaaaaa",
      email: "henry@gmail.com",
      phone: "333-333-333",
    },
  ],
};

export default function (state = initialState, action) {
  switch (action.type) {
    case "TEST_ACTION":
      return {
        ...state,
      };
    default:
      console.log("testing action");
      return state;
  }
}

所以,我从 reducer 文件中的 console.log 语句中注意到,对于每个联系人,contactReducer 和 testReducer 的函数都使用以下行调用:

  getContacts: () => dispatch({ type: "TEST_ACTION" }),
});

如果我有多个 reducer,但我只想调用它们的一个函数进行调度,我该怎么办?

【问题讨论】:

  • 您的操作type 在您的所有reducer 中应该是唯一的。在 Redux 中,store 的所有 reducer 都会处理每一个动作——这就是为什么默认情况下只返回之前的状态。
  • 啊,好吧,那是有道理的。我是 redux 的新手,所以我想也许两个 reducer 可能共享相同类型的操作。
  • 如果两家商店都对相同的操作做出反应,您绝对可以这样做,但请注意它,以防这不是您想要做的。
  • 好的,非常感谢您的澄清
  • 顺便问一下,这能回答你的问题吗? All reducers will be invoked when an action is dispatched?

标签: reactjs redux reducers redux-reducers


【解决方案1】:

combineReducers, 是redux中的一个辅助函数,可以帮助你划分你的reducer。看看这个链接:LINK

【讨论】:

    猜你喜欢
    • 2020-09-02
    • 2020-05-28
    • 2021-11-29
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多