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

Strapi+React分页异常:点击Next页码递增但数据为空

Strapi分页切换后数据为空的问题修复

核心问题分析

你遇到的问题根源是重复实现了分页逻辑:Strapi的分页API会根据你传入的pagination[page]和pagination[pageSize]参数,直接返回对应页码的完整数据,但你在前端又通过slice(startIndex, endIndex)对接口返回的数据做了二次截取。当切换到第2页时,接口已经返回了第2页的25条数据,你却从索引25的位置开始截取,自然得到空数组。

修复步骤

1. 移除前端不必要的分页截取逻辑

删掉startIndex、endIndex和currentPageData的定义,直接使用接口返回的customerData.data即可,因为Strapi已经帮你做好了分页数据筛选。

2. 修正totalPages计算(避免空值报错)

在customerData未加载完成时,给totalPages设置默认值,避免Math.ceil传入undefined导致报错。

3. 优化加载状态处理

优先判断isLoading状态,避免在数据加载过程中渲染错误内容。

修改后的关键代码

const Customers = () => {
  const [modalOpen, setModalOpen] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 25; 
  const { data: customerData, isLoading } = useGetCustomers({page: currentPage, pageSize:pageSize});

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<IAddCustomerProps>();

  // 修正totalPages计算,添加默认值避免空值报错
  const totalPages = customerData ? Math.ceil(customerData.meta.pagination.total / pageSize) : 1;

  const handleNextPage = () => {
    setCurrentPage((prevPage) => prevPage + 1);
  };

  const handlePreviousPage = () => {
    setCurrentPage((prevPage) => prevPage - 1);
  };

  const columns: string[] = [
    "Name",
    "Email",
    "Birthday",
    "Phone Number",
    "Card Number",
    "Points",
  ];

  const handleModalOpen = () => {
    setModalOpen(true);
  };

  // 直接使用接口返回的当前页数据,无需二次截取
  const data: any[] = customerData?.data.map((customer: any) => [
    customer.attributes.name,
    customer.attributes.email,
    customer.attributes.birthday,
    customer.attributes.tel,
    customer.attributes.card.data.attributes.number,
    customer.attributes.card.data.attributes.points,
  ]) || [];

  const onSubmit: SubmitHandler<IAddCustomerProps> = (data: any) => {
    console.log(data);
    // Add your submit logic here
  };

  return (
    <DashboardLayout>
      <div>
        <div className="w-full flex justify-end my-3">
          <Button onClick={handleModalOpen} color="dark">
            Add Customer
          </Button>
        </div>
        <Modal
          onClose={() => setModalOpen(false)}
          popup
          size="md"
          show={modalOpen}
          dismissible
        >
          {/* Modal content */}
        </Modal>

        {/* 优先处理加载状态,再渲染数据 */}
        {isLoading ? (
          <p>Loading customer data...</p>
        ) : customerData ? (
          <>
            <Table columns={columns} data={data} />
            {/* Pagination */}
            <div className="pagination text-center p-2 mt-3">
              <button
                disabled={currentPage === 1}
                onClick={handlePreviousPage}
                className="bg-gray-200 p-2 rounded-lg"
              >
                Previous
              </button>
              <span className="px-4">{`Page ${currentPage} of ${totalPages}`}</span>
              <button
                disabled={currentPage === totalPages}
                onClick={handleNextPage}
                className="bg-gray-200 p-2 rounded-lg"
              >
                Next
              </button>
            </div>
          </>
        ) : (
          <p>No customer data found</p>
        )}
      </div>
    </DashboardLayout>
  );
};

额外优化建议

  • 修正API请求中的引号转义问题:把\"customers?populate=card\"改成'customers?populate=card'或反引号,避免不必要的转义错误。
  • 给useQuery添加keepPreviousData: true配置,切换页码时保留上一页数据,避免页面闪烁:
export const useGetCustomers = ({ page, pageSize }: CustomerPaginationProps) => {
    const { data, isLoading, error, refetch } = useQuery(
      ["customers", page, pageSize],
      () => GetCustomers({ page, pageSize }),
      {
        onError: (error) => {
          if (error instanceof AxiosError) {
            console.log("customers error", error);
          }
        },
        keepPreviousData: true // 添加此行
      }
    );
  
    return { data, isLoading, error, refetch };
};

内容的提问来源于stack exchange,提问作者Nicholas Darko Brown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:40:04