You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Query实现双向无限列表:如何向query函数传递查询方向参数?

解决useInfiniteQuery双向无限列表的查询方向传递问题

方案1:在pageParam中显式加入方向标识

直接在传递给queryFn的pageParam里添加direction字段,明确告诉后端是向前还是向后查询:

const { data, fetchNextPage, fetchPreviousPage } = useInfiniteQuery({
  queryKey: ['bidirectional-items'],
  queryFn: async ({ pageParam }) => {
    // 把cursor和direction一起传给后端
    const res = await fetch(`/api/items?cursor=${pageParam.cursor}&direction=${pageParam.direction}`);
    return res.json();
  },
  initialPageParam: { cursor: null, direction: 'next' },
  getNextPageParam: (lastPage) => {
    // 向后翻页时,构造带direction: 'next'的pageParam
    return lastPage.hasMoreNext ? { cursor: lastPage.nextCursor, direction: 'next' } : undefined;
  },
  getPreviousPageParam: (firstPage) => {
    // 向前翻页时,构造带direction: 'prev'的pageParam
    return firstPage.hasMorePrev ? { cursor: firstPage.prevCursor, direction: 'prev' } : undefined;
  },
});

后端拿到direction参数后,就能对应调整查询逻辑:比如next取游标之后的记录,prev取游标之前的。

方案2:用语义化参数区分方向(无需单独传direction)

如果后端支持,可以用before和after这类语义化参数替代通用cursor,通过参数名隐含查询方向:

const { data, fetchNextPage, fetchPreviousPage } = useInfiniteQuery({
  queryKey: ['bidirectional-items'],
  queryFn: async ({ pageParam }) => {
    const params = new URLSearchParams();
    if (pageParam.after) params.append('after', pageParam.after);
    if (pageParam.before) params.append('before', pageParam.before);
    const res = await fetch(`/api/items?${params.toString()}`);
    return res.json();
  },
  initialPageParam: { after: null },
  getNextPageParam: (lastPage) => {
    return lastPage.hasMoreNext ? { after: lastPage.nextCursor } : undefined;
  },
  getPreviousPageParam: (firstPage) => {
    return firstPage.hasMorePrev ? { before: firstPage.prevCursor } : undefined;
  },
});

后端通过判断请求中是before还是after参数,来决定查询游标前后的记录,这种方式更符合RESTful风格。

内容的提问来源于stack exchange,提问作者asliwinski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:07:58