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

react-query中useInfiniteQuery无法追加数据问题求助

问题描述

使用json-server提供的数据,通过react-query(非TanStack Query)实现无限查询功能时,程序无报错,但始终重复显示相同数据。已确认pageParam能正常递增,按钮禁用逻辑正常,却无法追加新数据。

代码与数据

组件代码

import { useInfiniteQuery } from "react-query";
import axios from "axios";
import React from "react";

const fetchUsers = ({ pageParam = 1 }) =
  axios.get(`http://localhost:1000/users?_page=${pageParam}&_limit=2`);

const InfiniteQuery = () => {
  const {
    isLoading,
    isError,
    error,
    data,
    hasNextPage,
    fetchNextPage,
    isFetching,
    isFetchingNextPage,
  } = useInfiniteQuery(["users"], fetchUsers, {
    getNextPageParam: (_lastPage, pages) => {
      if (pages.length < 3) {
        return pages.length + 1;
      } else {
        return undefined;
      }
    },
  });
  console.log("data", data);

  if (isLoading) {
    return <h2>Loading...</h2>;
  }
  if (isError) {
    return <h2>{error.message}</h2>;
  }
  return (
    <div>
      {data?.pages.map((usrGrp, index) => (
        <React.Fragment key={index}>
          {usrGrp?.data.map((usr) => (
            <div key={usr.id}>
              <h2>{usr.name}</h2>
              <hr />
            </div>
          ))}
        </React.Fragment>
      ))}
      <div>
        <button disabled={!hasNextPage} onClick={fetchNextPage}>
          Load more
        </button>
      </div>
      <div>{isFetching && !isFetchingNextPage ? "Fetching..." : null}</div>
    </div>
  );
};

export default InfiniteQuery;

JSON数据(json-server)

{
  "users": [
    {
      "id": "1",
      "name": "John Doe"
    },
    {
      "id": "2",
      "name": "Mary James"
    },
    {
      "id": "3",
      "name": "Tom Brown"
    },
    {
      "id": "4",
      "name": "Ron Watson"
    },
    {
      "id": "5",
      "name": "Luna Paul"
    },
    {
      "id": "6",
      "name": "Richard Harris"
    }
  ]
}
问题排查与修复

核心错误:fetchUsers函数定义语法错误

你在定义fetchUsers时,把箭头函数的=>写成了=,导致fetchUsers并不是一个可复用的请求函数,而是直接赋值为第一次执行axios.get的Promise结果,所以每次调用都会返回相同的初始数据。

修复代码

将fetchUsers的定义修正为正确的箭头函数:

const fetchUsers = ({ pageParam = 1 }) => 
  axios.get(`http://localhost:1000/users?_page=${pageParam}&_limit=2`);

可选优化:动态判断是否有下一页

当前getNextPageParam通过固定判断pages.length <3来决定是否有下一页,不够灵活。可以利用json-server返回的响应头中的X-Total-Count来动态计算:

getNextPageParam: (lastPage, pages) => {
  // json-server会在响应头返回总数据条数
  const totalCount = Number(lastPage.headers['x-total-count']);
  const currentPage = pages.length;
  const perPage = 2;
  // 如果当前页数据还没取完,返回下一页页码
  return currentPage * perPage < totalCount ? currentPage + 1 : undefined;
}

这样无论数据总量如何变化,都能自动判断是否还有下一页,不需要硬编码页数限制。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:47:16