Suspense
信息
- 确保您使用的是最新版本的 React
- 如果您在 Next.js 中使用 tRPC 的自动 SSR,如果查询失败,整个页面将在服务器上崩溃,即使您有
<ErrorBoundary />
用法
提示
useSuspenseQuery
和 useSuspenseInfiniteQuery
都返回一个 [data, query]
元组,以便轻松直接使用数据并将变量重命名为描述性名称
useSuspenseQuery()
tsx
// @filename: pages/index.tsximportReact from 'react';import {trpc } from '../utils/trpc';functionPostView () {const [post ,postQuery ] =trpc .post .byId .useSuspenseQuery ({id : '1' });return <>{/* ... */}</>;}
tsx
// @filename: pages/index.tsximportReact from 'react';import {trpc } from '../utils/trpc';functionPostView () {const [post ,postQuery ] =trpc .post .byId .useSuspenseQuery ({id : '1' });return <>{/* ... */}</>;}
useSuspenseInfiniteQuery()
tsx
// @filename: pages/index.tsximport React from 'react';import { trpc } from '../utils/trpc';function PostView() {const [pages, allPostsQuery] = trpc.post.all.useSuspenseInfiniteQuery({},{getNextPageParam(lastPage) {return lastPage.nextCursor;},},);const { isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =allPostsQuery;return <>{/* ... */}</>;}
tsx
// @filename: pages/index.tsximport React from 'react';import { trpc } from '../utils/trpc';function PostView() {const [pages, allPostsQuery] = trpc.post.all.useSuspenseInfiniteQuery({},{getNextPageParam(lastPage) {return lastPage.nextCursor;},},);const { isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =allPostsQuery;return <>{/* ... */}</>;}
useSuspenseQueries()
Suspense 等同于 useQueries()
。
tsx
const Component = (props: { postIds: string[] }) => {const [posts, postQueries] = trpc.useSuspenseQueries((t) =>props.postIds.map((id) => t.post.byId({ id })),);return <>{/* [...] */}</>;};
tsx
const Component = (props: { postIds: string[] }) => {const [posts, postQueries] = trpc.useSuspenseQueries((t) =>props.postIds.map((id) => t.post.byId({ id })),);return <>{/* [...] */}</>;};