TypeError:没有重载匹配Next.js中的getQueriesData函数13

w6mmgewl  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(170)

我在使用Next.js 13中的getQueriesData函数与React Query时遇到了TypeScript错误。下面是我的代码:

// app/products.tsx

import { getQueryClient } from "@/app/providers/getQueryClient";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import React from "react";

export interface ProductResponse {
  // Interface definition...
}

// Function definition...

export const ProductList = () => {
  const queryClient = getQueryClient();
  const { data, isLoading, isFetching, error } = useQuery({
    queryKey: ["hydrate-users"],
    queryFn: () => getProducts(),
  });

  return (
    <div>
      <button onClick={() => {
          queryClient.getQueriesData("hydrate-users");
      }}>Revalidate</button>
      {/* Rest of the code */}
    </div>
  );
};

我的queryClient.tsx:

// app/getQueryClient.jsx
import { QueryClient } from "@tanstack/react-query";
import { cache } from "react";

const getQueryClient = cache(() => new QueryClient());
export default getQueryClient;

我尝试在queryClient示例上调用getQueryesData函数,但收到以下错误:

No overload matches this call.
  Overload 1 of 2, '(queryKey: QueryKey): [QueryKey, unknown][]', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'QueryKey'.
  Overload 2 of 2, '(filters: QueryFilters): [QueryKey, unknown][]', gave the following error.
    Type '"hydrate-users"' has no properties in common with type 'QueryFilters'.
rjee0c15

rjee0c151#

  • "@tanstack/react-query”:“^4.29.12”*

让我们看看getQueriesData()方法的TS重载签名和实现签名:

getQueriesData<TQueryFnData = unknown>(
  queryKey: QueryKey,
): [QueryKey, TQueryFnData | undefined][]
getQueriesData<TQueryFnData = unknown>(
  filters: QueryFilters,
): [QueryKey, TQueryFnData | undefined][]
getQueriesData<TQueryFnData = unknown>(
  queryKeyOrFilters: QueryKey | QueryFilters,
): [QueryKey, TQueryFnData | undefined][] {
  return this.getQueryCache()
    .findAll(queryKeyOrFilters)
    .map(({ queryKey, state }) => {
      const data = state.data as TQueryFnData | undefined
      return [queryKey, data]
    })
}

QueryKey类型,正如你所看到的,queryKey是一个只读数组。

export type QueryKey = readonly unknown[]

react-query检查queryKey参数使用isQueryKey函数,实现:

export function isQueryKey(value: unknown): value is QueryKey {
  return Array.isArray(value)
}

可以通过传递queryKey数组来匹配第一个重载签名

import { QueryClient } from "@tanstack/react-query";

const queryClient = new QueryClient();
queryClient.getQueriesData(['hydrate-users'])

相关问题