【发布时间】:2019-11-23 10:37:01
【问题描述】:
在 react typescript 中,如何将两个接口分配给 reducer 函数:标准 {type: string, payload: object} 和 redux-thunk?
reducer.ts
interface IReduxThunkAction {
(dispatch: any): Promise<void>;
}
interface IActionPayload {
type?: string;
payload?: any;
}
type IAction = IActionPayload | IReduxThunkAction;
const reducer = (prevState = initialState, action: IAction): IInitialState => {
switch (action.type) {
case UPDATE_ITEMS:
return updateItemsData(prevState, action.payload);
default:
return prevState;
}
};
这是给我的错误:
类型“IAction”上不存在属性“类型”。 类型“IReduxThunkAction”上不存在属性“类型”。
actions.ts
export const getItems = (
term: string
): ThunkAction<Promise<void>, {}, {}, AnyAction> => {
return (dispatch: ThunkDispatch<{}, {}, AnyAction>): Promise<void> => {
return searchItems(term)
.then(response => {
const { results } = response.data;
dispatch(updateItems(results));
})
.catch(() => {
dispatch(fetchError());
});
};
};
ItemsList.tsx
// function with useReducer hook inside it
const [reducerState, dispatch] = useReducer(reducer, initialState);
// more code...
const handleSearch = (event: { preventDefault: () => void }) => {
event.preventDefault();
if (validateInput(state.value)) {
dispatch(actions.changeSpinnerState());
return dispatch(actions.getItems(state.value))
.then(() =>
dispatch(actions.changeSpinnerState())
);
}
};
这里它告诉我在线调度(actions.getItems(state.value)):
“ThunkAction、{}、{}、AnyAction>”类型的参数不能分配给“IAction”类型的参数。 类型“ThunkAction, {}, {}, AnyAction>”不可分配给类型“IReduxThunkAction”。
【问题讨论】:
-
为什么要将第二个接口分配给reducer?为什么需要在 reducer 中调度?
-
@kinduser 我不需要在减速器内调度,但如果我只分配 IActionPayload 则从 ItemsList.tsx 文件中调度(actions.getItems(state.value))会抱怨......我该怎么做那么呢?
-
你的
getItemsfunc 让我有点吃惊,你为什么要派出消息?为什么要在动作创建者中处理副作用?在我的生活中从未在任何地方看到过这种方法。 -
@kinduser 我编辑了我正在使用钩子的代码,所以它来自 useReducer 钩子
标签: reactjs typescript react-redux react-hooks react-typescript