【发布时间】:2022-08-05 12:11:15
【问题描述】:
我正在使用 react-async-hook 来获取 React 组件中的 API 数据。
const popularProducts = useAsync(fetchPopularProducts, []);
fetchPopularProducts() 是使用 fetch 进行 api 调用的异步方法:
export async function fetchPopularProducts(
limit = 10,
start = 1
): Promise<Response<PopularProduct[]>> {
const apiUrl = `${API_BASE_URL}/rest/V1/fastlaneapi/product/popular? limit=${limit}&start=${start}`;
const res = await fetch(apiUrl);
const json = await res.json();
if (res.status !== 200) {
const message = json.message !== undefined ? json.message : \"\";
throw new RequestError(message, res.status);
}
return json;
}
如何用 TypeScript 定义,useAsync 钩子的响应,我在下面尝试过这样但它不起作用:
const popularProducts = useAsync<AsyncState<Response<PopularProduct[]>>>
(fetchPopularProducts, []);
AsyncState 类型来自 react-async-hook 库,它看起来像这样
export declare type AsyncState<R> = {
status: AsyncStateStatus;
loading: boolean;
error: Error | undefined;
result: R | undefined;
};
因此,我尝试提供来自 fetchPopularProducts() 方法的结果,而不是 \"R\",它是:Response<PopularProduct[]>,但它不起作用。
错误信息:
TS2769: No overload matches this call.
Overload 1 of 2, \'(asyncFunction: () => Promise<AsyncState<Response<PopularProduct[]>>>, params: UnknownArgs, options?: Partial<...>): UseAsyncReturn<...>\', gave the following error.
Argument of type \'(limit?: number, start?: number) => Promise<Response<PopularProduct[]>>\' is not assignable to parameter of type \'() => Promise<AsyncState<Response<PopularProduct[]>>>\'.
Type \'Promise<Response<PopularProduct[]>>\' is not assignable to type \'Promise<AsyncState<Response<PopularProduct[]>>>\'.
Type \'Response<PopularProduct[]>\' is missing the following properties from type \'AsyncState<Response<PopularProduct[]>>\': status, loading, error, result
Overload 2 of 2, \'(asyncFunction: (...args: UnknownArgs) => Promise<AsyncState<Response<PopularProduct[]>>>, params: UnknownArgs, options?: Partial<...>): UseAsyncReturn<...>\', gave the following error.
Argument of type \'(limit?: number, start?: number) => Promise<Response<PopularProduct[]>>\' is not assignable to parameter of type \'(...args: UnknownArgs) => Promise<AsyncState<Response<PopularProduct[]>>>\'.
Type \'Promise<Response<PopularProduct[]>>\' is not assignable to type \'Promise<AsyncState<Response<PopularProduct[]>>>\'.
标签: reactjs typescript react-async