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.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from '../server';export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'YOUR_API_URL' })],});
utils/trpc.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from '../server';export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'YOUR_API_URL' })],});
components/PostList.tsxtsximport {useQuery } from '@tanstack/react-query';import {trpc } from '../utils/trpc';functionPostList () {const {data } =useQuery ({queryKey : ['posts'],queryFn : () =>trpc .post .list .query (),});data ; // Post[]// ...}
components/PostList.tsxtsximport {useQuery } from '@tanstack/react-query';import {trpc } from '../utils/trpc';functionPostList () {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 functionIndexPage () {consthelloQuery =trpc .hello .useQuery ({name : 'Bob' });constgoodbyeMutation =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 functionIndexPage () {consthelloQuery =trpc .hello .useQuery ({name : 'Bob' });constgoodbyeMutation =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 应用的类型安全