跳至主内容
版本:11.x
非官方测试版翻译

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

tRPC 客户端

使用"Vanilla" tRPC客户端调用API procedures就像调用本地函数一样,为您提供无缝的开发体验。

ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
 
const client = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'http://localhost:3000' })],
});
 
const bilbo = await client.getUser.query('id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
 
const client = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'http://localhost:3000' })],
});
 
const bilbo = await client.getUser.query('id_bilbo');
// => { id: 'id_bilbo', name: 'Bilbo' };

何时使用Vanilla客户端?

您可能会在两种场景中使用此客户端:

  • 与我们尚未提供官方集成的前端框架配合使用

  • 与使用TypeScript编写的独立后端服务配合使用

何时不应使用Vanilla客户端?

  • 虽然您_可以_使用客户端从React组件中调用procedures,但通常应该使用我们的TanStack React Query集成。该集成提供了许多额外功能,例如管理加载和错误状态、缓存以及失效的能力。

  • 当调用同一API实例中的procedures时,我们建议不要使用此客户端,因为调用需要经过网络层传输。关于在当前API中调用procedure的完整建议,您可以在此阅读更多内容