我正在尝试在 Typescript 中使用 useQuery
Posted
技术标签:
【中文标题】我正在尝试在 Typescript 中使用 useQuery【英文标题】:I am trying to work with useQuery in Typescript 【发布时间】:2021-11-17 16:03:12 【问题描述】:在 typescript/react 中使用 useQuery
挂钩时,我收到一条错误消息,指出 Argument of type '(param: Param) => Promise<any>'
不可分配给 'QueryFunction<IResponsePlanets, QueryKey>'
类型的参数。
但请记住,onSuccess 函数在这里起作用。即使我得到一个错误
这是参数的接口
type Param =
pageParam?: undefined;
queryKey: [string, page: number ];
这是异步函数
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????')
;
【问题讨论】:
请提供复制品(例如codesandbox),否则很难说 【参考方案1】:问题在于你的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>
【讨论】:
以上是关于我正在尝试在 Typescript 中使用 useQuery的主要内容,如果未能解决你的问题,请参考以下文章