useQueries()
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
useQueries 钩子可通过单次调用同时获取数量可变的多个查询。
该钩子的主要用途是批量获取多个通常类型相同的查询。例如,当您获取待办事项 ID 列表后,可以在 useQueries 钩子中遍历这些 ID,调用按 ID 获取详情的端点来取得每个待办事项的详细信息。
备注
虽然可以在 useQueries 钩子中获取多种类型的数据,但与使用多个 useQuery 调用相比优势不大,除非启用 suspense 选项——因为 useQueries 可并行触发 suspense,而多个 useQuery 调用会产生瀑布式加载。
用法
useQueries 钩子与 @tanstack/query useQueries 功能相同。唯一区别在于:不再传递包含 queries 数组的对象,而是改为传递一个接收 t 代理并返回查询数组的回调函数。
技巧
当使用 httpBatchLink 或 wsLink 时,以下操作最终只会向服务器发起 1 次 HTTP 调用。此外,若底层过程使用类似 Prisma 的 findUnique() 方法,它将自动批量处理并仅执行 1 次数据库查询。
tsximport {trpc } from './utils/trpc';constComponent = (props : {postIds : string[] }) => {constpostQueries =trpc .useQueries ((t ) =>props .postIds .map ((id ) =>t .post .byId ({id })),);return <>{/* [...] */}</>;};
tsximport {trpc } from './utils/trpc';constComponent = (props : {postIds : string[] }) => {constpostQueries =trpc .useQueries ((t ) =>props .postIds .map ((id ) =>t .post .byId ({id })),);return <>{/* [...] */}</>;};
为独立查询提供配置项
你可以在数组内任意查询调用的第二个参数传入常规查询选项,如enabled、suspense、refetchOnWindowFocus等。完整选项列表请参阅tanstack useQuery文档。
tsximport {trpc } from './utils/trpc';constComponent = () => {const [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }, {enabled : false }),t .greeting ({text : 'world' }),]);constonButtonClick = () => {post .refetch ();};return (<div ><h1 >{post .data &&post .data .title }</h1 ><p >{greeting .data ?.message }</p ><button onClick ={onButtonClick }>Click to fetch</button ></div >);};
tsximport {trpc } from './utils/trpc';constComponent = () => {const [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }, {enabled : false }),t .greeting ({text : 'world' }),]);constonButtonClick = () => {post .refetch ();};return (<div ><h1 >{post .data &&post .data .title }</h1 ><p >{greeting .data ?.message }</p ><button onClick ={onButtonClick }>Click to fetch</button ></div >);};
上下文
您也可传入可选的 React Query 上下文来覆盖默认设置。
tsxconst [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }),t .greeting ({text : 'world' })],myCustomContext ,);
tsxconst [post ,greeting ] =trpc .useQueries ((t ) => [t .post .byId ({id : '1' }),t .greeting ({text : 'world' })],myCustomContext ,);