跳至主内容
版本:9.x

React 使用指南

非官方测试版翻译

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

信息
  • 若使用 Next.js,请阅读《Next.js 使用指南》
  • 为确保从 Node.js 后端正确推断类型,请将前端与后端置于同一 monorepo 中

在现有 React 项目中集成 tRPC

服务端配置

1. 安装依赖

bash
yarn add @trpc/server zod
bash
yarn add @trpc/server zod
  • Zod:示例中多使用 Zod 进行输入验证,强烈推荐但非强制要求。可选用其他验证库(YupSuperstructio-ts等),任何包含 parsecreatevalidateSync 方法的对象均可使用

2. 启用严格模式

若使用 Zod 进行输入验证,需在 tsconfig.json 中启用严格模式:

json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}
json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}

若严格模式限制过强,至少需启用 strictNullChecks

json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}
json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}

3. 实现 appRouter

参照《快速入门》并查阅 @trpc/server 文档。完成 API 实现并通过 HTTP 监听后,继续下一步操作

客户端配置

tRPC 可完美兼容 Create React App!

1. 安装依赖

bash
yarn add @trpc/client @trpc/server @trpc/react react-query@3
bash
yarn add @trpc/client @trpc/server @trpc/react react-query@3
  • @trpc/server:作为 @trpc/client 的 peer dependency 需再次安装

  • Tanstack React Query:@trpc/react 是对 @tanstack/react-query 的轻量封装,需作为 peer dependency 安装

2. 创建 tRPC hooks

通过 createReactQueryHooks 基于 AppRouter 类型签名创建强类型 React hooks

utils/trpc.ts
tsx
// utils/trpc.ts
import { createReactQueryHooks } from '@trpc/react';
import type { AppRouter } from '../path/to/router.ts';
export const trpc = createReactQueryHooks<AppRouter>();
// => { useQuery: ..., useMutation: ...}
utils/trpc.ts
tsx
// utils/trpc.ts
import { createReactQueryHooks } from '@trpc/react';
import type { AppRouter } from '../path/to/router.ts';
export const trpc = createReactQueryHooks<AppRouter>();
// => { useQuery: ..., useMutation: ...}

3. 添加 tRPC providers

App.tsx 文件中:

App.tsx
tsx
import React, { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
url: 'http://localhost:5000/trpc',
// optional
headers() {
return {
authorization: getAuthCookie(),
};
},
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
App.tsx
tsx
import React, { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
url: 'http://localhost:5000/trpc',
// optional
headers() {
return {
authorization: getAuthCookie(),
};
},
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}

4. 数据获取

pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const hello = trpc.useQuery(['hello', { text: 'client' }]);
if (!hello.data) return <div>Loading...</div>;
return (
<div>
<p>{hello.data.greeting}</p>
</div>
);
}
pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const hello = trpc.useQuery(['hello', { text: 'client' }]);
if (!hello.data) return <div>Loading...</div>;
return (
<div>
<p>{hello.data.greeting}</p>
</div>
);
}