【发布时间】:2019-08-23 05:07:28
【问题描述】:
我需要一些关于 TS 的帮助。
我将我的一个项目迁移到 TypeSctipt。 该应用位于 React+Redux 堆栈上。
我有我的自定义 fetch 中间件,它是这样的:
import { Action, Dispatch, MiddlewareAPI } from 'redux';
import { TReduxAction } from 'interfaces';
export default ({ dispatch }: MiddlewareAPI) => (next: Dispatch<Action>) => (
action: TReduxAction
) => {
const { apiService, ...restActionProps } = action;
if (apiService === undefined) {
return next(action);
}
dispatch({ ...restActionProps, status: 'PENDING' });
return apiService(action.body).then(
(response: Response) => {
return next({
type: action.type,
data: response,
status: 'SUCCESS',
});
},
(error: Error) =>
next({
...action,
error,
status: 'ERROR',
})
);
};
我的动作创建者是这样的
const apiService = createApiService();
export function login(body: ILoginRequest) {
return {
type: types.LOGIN,
body,
apiService: apiService.login,
};
}
在应用程序中我像这样发送它
dispatch(login(payload));
而且效果很好。在 80% 的情况下
但是。有一个“但是”
有时我需要在组件级别做出响应(以显示错误或执行其他操作)
在我的 JS 版本中,我只是使用了.then()
dispatch(login(payload)).then((res) => { // do stuff });
因为中间件返回一个承诺
这不适用于 TS。 它说
Property 'then' does not exist on type '{ type: string; body: ILoginRequest; apiService: (request: ILoginRequest) => Promise<TLoginResponse | TLoginError>; }'
因为它不知道中间件返回一个promise。
那么如何使用异步中间件键入 dispatch 以使其工作?
【问题讨论】:
标签: reactjs typescript redux middleware