【发布时间】: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