React Query 集成(经典版)
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
技巧
本文档介绍的是我们"经典版"的 React Query 集成方案。虽然该方案仍受支持,但对于新建的 tRPC 项目,我们不再推荐将其与 TanStack React Query 搭配使用。建议改用全新的 TanStack React Query 集成方案。
tRPC 为 React 提供了一流集成方案。其底层实现是对流行库 @tanstack/react-query 的封装,因此我们建议您先熟悉 React Query 的使用,因为其文档对功能细节有更深入的讲解。
如果您正在使用 Next.js,建议改用我们针对 Next.js 的集成方案。
❓ Do I have to use an integration?
No! The integration is fully optional. You can use @tanstack/react-query using just a vanilla tRPC client, although then you'll have to manually manage query keys and do not get the same level of DX as when using the integration package.
utils/trpc.tstsexport const trpc = createTRPCClient<AppRouter>({links: [httpBatchLink({ url: 'YOUR_API_URL' })],});
utils/trpc.tstsexport const trpc = createTRPCClient<AppRouter>({links: [httpBatchLink({ url: 'YOUR_API_URL' })],});
components/PostList.tsxtsxfunction PostList() {const { data } = useQuery({queryKey: ['posts'],queryFn: () => trpc.post.list.query(),});data; // Post[]// ...}
components/PostList.tsxtsxfunction PostList() {const { data } = useQuery({queryKey: ['posts'],queryFn: () => trpc.post.list.query(),});data; // Post[]// ...}
tRPC 的 React Query 集成
该库支持直接在 React 组件中使用
pages/IndexPage.tsxtsximport { trpc } from '../utils/trpc';export default function IndexPage() {const helloQuery = trpc.hello.useQuery({ name: 'Bob' });const goodbyeMutation = trpc.goodbye.useMutation();return (<div><p>{helloQuery.data?.greeting}</p><button onClick={() => goodbyeMutation.mutate()}>Say Goodbye</button></div>);}
pages/IndexPage.tsxtsximport { trpc } from '../utils/trpc';export default function IndexPage() {const helloQuery = trpc.hello.useQuery({ name: 'Bob' });const goodbyeMutation = trpc.goodbye.useMutation();return (<div><p>{helloQuery.data?.greeting}</p><button onClick={() => goodbyeMutation.mutate()}>Say Goodbye</button></div>);}
与原生 React Query 的区别
该封装层为您抽象了 React Query 的以下功能:
-
Query Keys - 由 tRPC 根据您提供的输入参数自动生成和管理
- 如需获取 tRPC 计算出的查询键,可使用 getQueryKey 方法
-
默认类型安全 - 您在 tRPC 后端定义的类型将直接驱动 React Query 客户端的类型,确保整个 React 应用的类型安全