React 查询集成
tRPC 提供了与 React 的一流集成。从本质上讲,这只是非常流行的 @tanstack/react-query 的封装,因此我们建议你熟悉 React Query,因为他们的文档更深入地介绍了它的用法。
¥tRPC offers a first class integration with React. Under the hood this is simply a wrapper around the very popular @tanstack/react-query, so we recommend that you familiarise yourself with React Query, as their docs go in to much greater depth on its usage.
如果你使用 Next.js,我们建议使用 我们与它的整合
¥If you are using Next.js we recommend using our integration with that instead
tRPC React 查询集成
¥The tRPC React Query Integration
该库可以直接在 React 组件中使用
¥This library enables usage directly within React components
pages/IndexPage.tsxtsx
import { 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.tsxtsx
import { 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 查询的差异
¥Differences to vanilla React Query
封装器为你抽象了 React Query 的一些方面:
¥The wrapper abstracts some aspects of React Query for you:
查询键 - 这些是由 tRPC 根据你提供的过程输入代表你生成和管理的
¥Query Keys - these are generated and managed by tRPC on your behalf, based on the procedure inputs you provide
如果需要 tRPC 计算的查询 key,可以使用 getQueryKey
¥If you need the query key which tRPC calculates, you can use getQueryKey
默认类型安全 - 你在 tRPC 后端中提供的类型也会驱动 React Query 客户端的类型,从而为整个 React 应用提供安全性
¥Type safe by default - the types you provide in your tRPC Backend also drive the types of your React Query client, providing safety throughout your React app