如何将查询参数作为 React Query 的参数传递?

How can I pass a query param as an argument with React Query?

我正在使用 react-query 中的 useQuery,我需要动态传递查询参数

但我正在努力让这些类型正常工作

查询函数

interface ProfileResponse {
  photo: string
  about: string
  languages: number[] | null
  userid: number
}

export const get_profile_q= (uid: number) =>
  api.get(`/api/profile/${uid}`) as Promise<UseQueryResult<ProfileResponse>>

在组件内部使用

const { refetch: getProfile } = useQuery([PK.get_profile, {uid: 1}], get_profile_q)
// ^^^ throwing typescript error 

错误

Type '(uid: number) => Promise<UseQueryResult<ProfileResponse, unknown>>' 
has no properties in common with type 'Omit<UseQueryOptions<unknown, unknown, unknown, 
(string | { uid: number; })[]>, "queryKey">'.

这是一个可以执行动态查询的小示例 - 请注意查询 KEY 也是动态的。每个查询都必须有自己的键。

import { QueryClient, QueryClientProvider, useQuery } from "react-query";
import React from "react";
import "./styles.css";

interface IPost {
  userId: number;
  id: number;
  title: string;
  body: string;
}

const getData = async (id: number): Promise<IPost> => {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts/${id}`
  );
  return await response.json();
};

export const Example = () => {
  const [post, setPost] = React.useState<IPost>();
  const [postId, setPostId] = React.useState(0);

  const { data, refetch } = useQuery<IPost>(
    `queryKey${postId}`,
    async () => await getData(postId)
  );

  React.useEffect(() => {
    setPost(data);
  }, [data]);

  return (
    <>
      <input
        value="click 1"
        type="button"
        onClick={() => {
          setPostId(1);
          refetch();
        }}
      />
      <input
        value="click 2"
        type="button"
        onClick={() => {
          setPostId(2);
          refetch();
        }}
      />
      <div>{post?.title}</div>
    </>
  );
};

export default function App() {
  const queryClient = new QueryClient();

  return (
    <div className="App">
      <QueryClientProvider client={queryClient}>
        <h1>Hello CodeSandbox</h1>
        <Example />
      </QueryClientProvider>
    </div>
  );
}