跳到主要内容

Rest 分页

扩展列表​

要把结果追加到列表中而不是跳转到另一页,请使用 Resource.getList.getPage。它需要 paginationField。

import { useController, useLoading } from '@data-client/react';
import { PostResource } from './Post';

export default function LoadMore({ cursor }: { cursor: string }) {
  const ctrl = useController();
  const [loadPage, isPending] = useLoading(
    () => ctrl.fetch(PostResource.getList.getPage, { cursor }),
    [cursor],
  );
  return (
    <div className="loadMore">
      <button onClick={loadPage} disabled={isPending}>
        {isPending ? '...' : 'Load more'}
      </button>
    </div>
  );
}
实时预览

设置 Resource 的 paginationField 和 schema:

Post
export const PostResource = resource({
path: '/posts/:id',
schema: Post,
paginationField: 'cursor',
}).extend('getList', {
schema: { posts: new Collection([Post]), cursor: '' },
});

Github Issues 演示​

NextPage 会在点击时调用 RestEndpoint.getPage。滚动到预览底部,点击 "Load more" 即可追加下一页 issue。

探索 github-app 示例

更多演示

直接使用 RestEndpoint​

这个示例使用 Cosmos Hub 验证者列表。它只有一个 endpoint,因此使用 RestEndpoint 而不是 resource。借助 Collection 和 paginationField, RestEndpoint.getPage 会把下一页验证者追加到列表中。

import { useController, useLoading } from '@data-client/react';
import { getValidators } from './Validator';

export default function LoadMore({ next_key, limit }) {
  const ctrl = useController();
  const [handleLoadMore, isPending] = useLoading(
    () =>
      ctrl.fetch(getValidators.getPage, {
        'pagination.limit': limit,
        'pagination.key': next_key,
      }),
    [next_key, limit],
  );
  if (!next_key) return null;
  return (
    <div className="loadMore">
      <button onClick={handleLoadMore} disabled={isPending}>
        {isPending ? '...' : 'Load more'}
      </button>
    </div>
  );
}
实时预览

信封中的页码​

许多 API 会把每个列表包装在信封中:一个把数据和元数据放在一起的外层对象,比如 { "data": [...], "meta": { "page": 1, "totalPages": 4 } }。请把这个信封作为 schema,并把 Collection 放在 data 上,这样组件也能读取 meta:

Comment
import { Collection, Entity, RestEndpoint } from '@data-client/rest';

export class Comment extends Entity {
id = '';
body = '';
}

export const getComments = new RestEndpoint({
path: '/comments',
searchParams: {} as { discussionId: string; page?: number },
paginationField: 'page',
schema: {
data: new Collection([Comment]),
meta: { page: 0, totalPages: 0 },
},
});
CommentList
import { useController, useSuspense } from '@data-client/react';
import { getComments } from './Comment';

function CommentList({ discussionId }: { discussionId: string }) {
const { data, meta } = useSuspense(getComments, { discussionId });
const ctrl = useController();
const loadMore = () =>
ctrl.fetch(getComments.getPage, { discussionId, page: meta.page + 1 });
const add = (body: string) =>
ctrl.fetch(getComments.push, { discussionId }, { body });
// render data, a "Load more" button while meta.page < meta.totalPages, and a form calling add()
}
  • 第一次获取时不要带 page:getPage 根据去掉 paginationField 后的参数来查找要扩展的列表,因此用 page: 1 获取的列表是另一个列表,永远不会增长。
  • 每一页都会追加到 data 并替换 meta,因此 meta 始终描述最新的一页。
  • push 向同一路径发送 POST,并添加它返回的那一个 Comment。单独的创建 endpoint 可以通过 schema: getComments.schema.data.push 加入同一个列表,调用时传入 { discussionId }。

无限滚动​

无限滚动的 UI 因应用和平台(React Native 或 web)而异。这个示例使用一个 Pagination 组件,它通过调用回调来获取下一页。在 web 上,请基于 Intersection Observer 来构建它。

import { useSuspense, useController } from '@data-client/react';
import { PostResource } from 'resources/Post';
import Pagination from './Pagination';
import PostList from './PostList';

function NewsList() {
const { results, cursor } = useSuspense(PostResource.getList);
const ctrl = useController();

return (
<Pagination
onPaginate={() =>
ctrl.fetch(PostResource.getList.getPage, { cursor })
}
>
<PostList posts={results} />
</Pagination>
);
}

HTTP 头中的 token​

有些 API 会在 HTTP 头而不是响应体中发送分页 token。覆盖 getList 的 parseResponse(),把该头添加到响应中。在本例中,token 位于 link 头中。上面示例的其余部分保持不变。

import { resource } from '@data-client/rest';

export const ArticleResource = resource({
path: '/articles/:id',
schema: Article,
}).extend(Base => ({
getList: Base.getList.extend({
schema: { results: [Article], link: '' },
async parseResponse(response: Response) {
const results = await Base.getList.parseResponse(response);
if (
(response.headers && response.headers.has('link')) ||
Array.isArray(results)
) {
return {
link: response.headers.get('link'),
results,
};
}
return results;
},
}),
}));

代码组织​

如果许多 endpoint 采用相同的分页方式,请把这段逻辑放进一个自定义的 Endpoint 类中。

resources/PagingEndpoint.ts
import { Collection, RestEndpoint, type RestGenerics } from '@data-client/rest';

export class PagingEndpoint<
O extends RestGenerics = any,
> extends RestEndpoint<O> {
async parseResponse(response: Response) {
const results = await super.parseResponse(response);
if (
(response.headers && response.headers.has('link')) ||
Array.isArray(results)
) {
return {
link: response.headers.get('link'),
results,
};
}
return results;
}
}
resources/MyResource.ts
import { Collection, Entity, resource } from '@data-client/rest';

import { PagingEndpoint } from './PagingEndpoint';

export const MyResource = resource({
path: '/stuff/:id',
schema: MyEntity,
Endpoint: PagingEndpoint,
});