Redux 我可以在单独的 reducer 中使用一种操作类型吗?

Redux can I use one action type in separate reducers?

我的 Redux 应用程序中有一个情况,我目前有 3 个独立的 reducer 来处理从 api 获取数据。我的一个减速器的例子是:

const INITIAL_STATE = {
  data: [],
  loading: false,
  error: ''
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case GET_ALL_ORDERS_START:
      return {
        ...state,
        loading: true
      };
    case GET_ALL_ORDERS_SUCCESS:
      return {
        ...state,
        allOrders: action.payload,
        loading: false
      };
    case GET_ALL_ORDERS_FAIL:
      return {
        ...state,
        loading: false,
        error: action.payload
      };
    default:
      return state;
  }
};

注意加载和错误状态,这些在每个当前减速器中都是相同的,并且适用于我编写的涉及从 api.

获取数据的任何后续减速器

我想添加一个仅用于状态加载和错误片段的缩减器。其他 3 个将存储数据。

这会给我:

数据缩减器 x 3

const INITIAL_STATE = {
  data: []
  // any other state in the future
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case GET_ALL_ORDERS_SUCCESS:
      return {
        ...state,
        allOrders: action.payload
      };
    default:
      return state;
  }
};

加载/错误减少器(处理整个应用程序的加载/错误)

const INITIAL_STATE = {
  loading: false,
  error: ''
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case GET_ALL_ORDERS_START:
      return {
        ...state,
        loading: true
      };
    case GET_ALL_ORDERS_SUCCESS:
      return {
        ...state,
        loading: false
      };
    case GET_ALL_ORDERS_FAIL:
      return {
        ...state,
        loading: false,
        error: action.payload
      };
    default:
      return state;
  }
};

如您所见,这意味着 GET_ALL_ORDER_SUCCESS 操作类型将用于 2 个单独的 reducer。我的问题是,这样可以吗?还是违反惯例?

非常感谢。

我认为这很好。没有地方声明 Actions 和 Reducers 有一个 1:1 映射。事实上,Redux 的创建者明确表示它们之间没有关系,许多 reducer 可以对单个 action 做出反应,单个 reducer 可以对多个 action 做出反应。

我觉得他说得最好:https://github.com/reduxible/reduxible/issues/8

推文:https://twitter.com/dan_abramov/status/691608868628119552

相关SO:

如果我可以在两个或多个单独的 reducer 中使用相同的操作类型名称,我有一个类似的问题,如果没有非常特殊的情况,答案肯定是否定的。

为什么不呢?

即使我们在调度 action 时通过 combineReducers 函数组合它们之后单独编写 reducer,所有 reducer 都称为它们的 switch case 语句。

减速器一:

export const postReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case "SET_DATA":
      const { posts } = action.payload;
      return {
        ...state,
        posts: posts,
      };
  }
};

减速器二:

export const commentReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case "SET_DATA":
      const { comments } = action.payload;
      return {
        ...state,
        comments: comments,
      };
  }
};

所以当我们发送一个类型为 SET_DATA 的 action 时,两个 reducer 都会被调用 如果负载值为

{
  comments: ['comment one', 'comment two'] 
}

post reducer 会将其 post 设置为未定义。

更好的解决方案是像这样命名类型:

case "SET_POST_DATA":

case "SET_COMMENT_DATA": 

避免两个 reducer 的动作发生冲突。

惯例是当调用 action 时,只有一个 reducer 负责响应该 action,否则会引起其他开发人员的误解