【问题标题】:Problem setting up Redux with TypeScript when having multiple action payload types具有多种操作负载类型时,使用 TypeScript 设置 Redux 时出现问题
【发布时间】:2020-02-10 01:55:54
【问题描述】:

我正在尝试在 react 应用程序中使用 typescript 设置 redux,但我不明白我做错了什么。 这是我的类型和动作创建者。

export type FetchFamilyListError = {
  type: typeof FETCH_FAMILY_LIST_ERROR;
  payload: string;
};

export type FetchFamilyListSuccess = {
  type: typeof FETCH_FAMILY_LIST_SUCCESS;
  payload: Family[];
};

export type FamilyActions = FetchFamilyListError | FetchFamilyListSuccess;

export const fetchFamilyListError = (error: string): types.FamilyActions => ({
  type: types.FETCH_FAMILY_LIST_ERROR,
  payload: error
});

export const fetchFamilyListSuccess = (
  families: Family[]
): types.FamilyActions => ({
  type: types.FETCH_FAMILY_LIST_SUCCESS,
  payload: families
});

这里是减速器。

export type familyState = {
  families: Family[];
  filters: {
    size: number;
  };
  error: string | null;
};

const initialState: familyState = {
  families: [],
  filters: {
    size: 0
  },
  error: null
};

const familyReducer = (
  state = initialState,
  action: types.FamilyActions
): familyState => {
  const actions = {
    [types.FETCH_FAMILY_LIST_ERROR]: () =>
      produce(state, draftState => {
        draftState.error = action.payload; // <--- error here
      }),
    [types.FETCH_FAMILY_LIST_SUCCESS]: () => ({
      families: [],
      filters: {
        size: 0
      },
      error: null
    }),
    default: () => state
  };
  return actions[action.type] ? actions[action.type]() : actions.default();
};

我得到 键入'string | Family[]' 不可分配给类型 'string |空值'。 类型 'Family[]' 不可分配给类型 'string' 我猜这是因为 action.payload 可以是字符串或 Family[],我该如何解决这个问题?

我现在正在做这个

draftState.error =
          typeof action.payload === "string" ? action.payload : null;

但这似乎不是正确的方法。

【问题讨论】:

  • familyState 类型定义是什么样的?
  • 哦,对不起,我会把它添加到帖子中
  • 大家好,我是 Redux 维护者。我强烈鼓励您使用our new Redux Toolkit package,它已经在内部使用了 Immer,将为您生成这些动作创建器,并且旨在提供流畅的 TS 体验。
  • @markerikson 在使用魔法之前需要弄脏我的手。

标签: reactjs typescript redux


【解决方案1】:

我猜这是因为 action.payload 可以是字符串或 Family[]

正确,问题出在您的减速器中,action 被定义为 types.FamilyActions,因此当您尝试设置 draftState.error 时会出现歧义,因为 TS 无法确定它正在处理的操作。

鉴于我们知道它将基于动作类型是哪一个,您可以将有效负载转换为适当的类型,例如

draftState.error = action.payload as string

【讨论】:

  • 谢谢,我是 TypeScript 的新手,我正在寻找类似的东西。
  • @Nadhem 不用担心,我自己不是 TS 用户,但我为这个戴上编译器帽 :)
猜你喜欢
  • 2019-11-20
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 2016-11-29
  • 2022-06-28
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多