在typescript/react中使用useQuery
钩子时,我得到一个错误,说Argument of type '(param: Param) => Promise<any>'
不能分配给类型为'QueryFunction<IResponsePlanets, QueryKey>'
的参数。
但是记住onSuccess函数在这里工作。即使我得到一个错误
是参数
的接口type Param = {
pageParam?: undefined;
queryKey: [string, { page: number }];
}
这是async函数
const fetchFunction = async (param: Param) => {
const [key, { page }] = param.queryKey;
const response = await fetch(`https://swapi.dev/api/planet/?page=${page}`);
return response.json();
};
是useQuery钩子
const { status, error, data } = useQuery<IResponsePlanets, Error>(["planets", { page: 1 }], fetchFunction, {
staleTime: 5000,
onSuccess: () => {
console.log('working👍')
}
};
问题在你的fetchFunction
签名
const fetchFunction = async (param: Param) => {
^^^^^
const [key, { page }] = param.queryKey;
const response = await fetch(`https://swapi.dev/api/planet/?page=${page}`);
return response.json();
};
参数类型应为QueryFunctionContext<Param>