在react typescript中,我如何为动作分配两个接口:标准{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”上不存在属性“ type”。
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'。
答案 0 :(得分:0)
好,我解决了:
ItemsList.tsx
const [reducerState, dispatch] = useReducer(reducer, initialState);
// more code...
const handleSearch = (event: { preventDefault: () => void }) => {
event.preventDefault();
if (validateInput(state.value)) {
dispatch(actions.changeSpinnerState());
dispatch(actions.changeSpinnerState());
actions.getItems(state.value)(dispatch as IActionPayload);
}
};
actions.ts:
export const getItems = (term: string): React.Dispatch<IActionPayload> => {
return (dispatch: any): Promise<void> => {
return searchItems(term)
.then(response => {
const { results } = response.data;
dispatch(actions.changeSpinnerState());
dispatch(updateItems(results));
})
.catch(() => {
dispatch(fetchError());
});
};
};
reducer.ts:
const reducer = (prevState = initialState, action: IActionPayload
): IInitialState => {
switch (action.type) {
case UPDATE_ITEMS:
return updateItemsData(prevState, action.payload);
default:
return prevState;
}
};