获取查询键
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
我们提供了 getQueryKey 辅助函数,它接受一个 router 或 procedure 作为参数,使您能够轻松地为原生函数提供正确的查询键。
tsx// Queriesdeclare functiongetQueryKey (procedure :AnyQueryProcedure ,input ?:DeepPartial <TInput >,type ?:QueryType , /** @default 'any' */):TRPCQueryKey ;// Routersdeclare functiongetQueryKey (router :AnyRouter ,):TRPCQueryKey ;typeQueryType = "query" | "infinite" | "any";// for useQuery ──┘ │ │// for useInfiniteQuery ────┘ │// will match all ───────────────────────┘
tsx// Queriesdeclare functiongetQueryKey (procedure :AnyQueryProcedure ,input ?:DeepPartial <TInput >,type ?:QueryType , /** @default 'any' */):TRPCQueryKey ;// Routersdeclare functiongetQueryKey (router :AnyRouter ,):TRPCQueryKey ;typeQueryType = "query" | "infinite" | "any";// for useQuery ──┘ │ │// for useInfiniteQuery ────┘ │// will match all ───────────────────────┘
备注
仅当使用 any 查询类型的方法在 react query 中启用了模糊匹配时,才会匹配缓存中的所有查询。更多背景信息请参阅 TanStack/query#5111 (评论)。
tsximport {useIsFetching ,useQueryClient } from '@tanstack/react-query';import {getQueryKey } from '@trpc/react-query';import {trpc } from './utils/trpc';functionMyComponent () {constqueryClient =useQueryClient ();constposts =trpc .post .list .useQuery ();// See if a query is fetchingconstpostListKey =getQueryKey (trpc .post .list ,undefined , 'query');constisFetching =useIsFetching ({queryKey :postListKey });// Set some query defaults for an entire routerconstpostKey =getQueryKey (trpc .post );queryClient .setQueryDefaults (postKey , {staleTime : 30 * 60 * 1000 });// ...}
tsximport {useIsFetching ,useQueryClient } from '@tanstack/react-query';import {getQueryKey } from '@trpc/react-query';import {trpc } from './utils/trpc';functionMyComponent () {constqueryClient =useQueryClient ();constposts =trpc .post .list .useQuery ();// See if a query is fetchingconstpostListKey =getQueryKey (trpc .post .list ,undefined , 'query');constisFetching =useIsFetching ({queryKey :postListKey });// Set some query defaults for an entire routerconstpostKey =getQueryKey (trpc .post );queryClient .setQueryDefaults (postKey , {staleTime : 30 * 60 * 1000 });// ...}
变更
与查询类似,我们为变更提供了 getMutationKey 辅助函数。其底层实现与 getQueryKey 相同(实际上您也可以将 getQueryKey 用于变更),唯一的区别在于语义层面。
tsximport { getMutationKey } from '@trpc/react-query';const mutationKey = getMutationKey(trpc.user.create);
tsximport { getMutationKey } from '@trpc/react-query';const mutationKey = getMutationKey(trpc.user.create);