跳至主内容
版本:10.x

useQueries()

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

useQueries 钩子可通过单次调用同时获取数量可变的多个查询。

该钩子的主要用途是批量获取多个通常类型相同的查询。例如,当您获取待办事项 ID 列表后,可以在 useQueries 钩子中遍历这些 ID,调用按 ID 获取详情的端点来取得每个待办事项的详细信息。

备注

虽然可以在 useQueries 钩子中获取多种类型的数据,但与使用多个 useQuery 调用相比优势不大,除非启用 suspense 选项——因为 useQueries 可并行触发 suspense,而多个 useQuery 调用会产生瀑布式加载。

用法

该 useQueries 钩子与 @tanstack/query useQueries 功能相同,唯一区别在于您需要传入返回查询数组的函数,而非在对象参数内直接传递查询数组。

技巧

当使用 httpBatchLinkwsLink 时,以下操作最终只会向服务器发起 1 次 HTTP 调用。此外,若底层过程使用类似 Prisma 的 findUnique() 方法,它将自动批量处理并仅执行 1 次数据库查询。

tsx
const Component = (props: { postIds: string[] }) => {
const postQueries = trpc.useQueries((t) =>
props.postIds.map((id) => t.post.byId({ id })),
);
return <>{/* [...] */}</>;
};
tsx
const Component = (props: { postIds: string[] }) => {
const postQueries = trpc.useQueries((t) =>
props.postIds.map((id) => t.post.byId({ id })),
);
return <>{/* [...] */}</>;
};

为独立查询提供配置项

您可以为数组中任意查询调用的第二个参数传递标准查询选项,例如 enabled(启用状态)、suspense( suspense 模式)、refetchOnWindowFocus(窗口聚焦重获取)等。完整选项列表请参阅 tanstack useQuery 文档。

tsx
const Component = () => {
const [post, greeting] = trpc.useQueries((t) => [
t.post.byId({ id: '1' }, { enabled: false }),
t.greeting({ text: 'world' }),
]);
const onButtonClick = () => {
post.refetch();
};
return (
<div>
<h1>{post.data && post.data.title}</h1>
<p>{greeting.data.message}</p>
<button onClick={onButtonClick}>Click to fetch</button>
</div>
);
};
tsx
const Component = () => {
const [post, greeting] = trpc.useQueries((t) => [
t.post.byId({ id: '1' }, { enabled: false }),
t.greeting({ text: 'world' }),
]);
const onButtonClick = () => {
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 上下文来覆盖默认设置。

tsx
const [post, greeting] = trpc.useQueries(
(t) => [t.post.byId({ id: '1' }), t.greeting({ text: 'world' })],
myCustomContext,
);
tsx
const [post, greeting] = trpc.useQueries(
(t) => [t.post.byId({ id: '1' }), t.greeting({ text: 'world' })],
myCustomContext,
);