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

使用React与Axios Hooks实现分页时如何遍历数组渲染RuleSetsItem组件

解决方案

1. 优化分页数据存储逻辑,增加空值兜底

在存储每页数据时,为接口返回值增加空数组兜底,避免undefined/null存入数据集:

useEffect(() => {
  setDataPerPage((d) => ({ ...d, [page]: data ?? [] }));
}, [page, data]);

2. 合并多页数据后遍历渲染

在渲染前先将所有分页的数组合并为一维数组,过滤无效值后用原逻辑遍历即可:

import React, { useState, useEffect } from "react";
import useAxios from "axios-hooks";
// 请根据实际情况引入RuleSetsItem组件和RuleSetType类型

function App() {
  const [dataPerPage, setDataPerPage] = useState<Record<number, RuleSetType[]>>({});
  const [page, setPage] = useState(1);
  const [{ data, loading, error }] = useAxios({
    url: "http://localhost:6366/api/rule-sets",
    params: { page: page }
  });

  useEffect(() => {
    setDataPerPage((d) => ({ ...d, [page]: data ?? [] }));
  }, [page, data]);

  // 合并所有分页数据为一维数组
  const allRuleSets = Object.values(dataPerPage).filter(Boolean).flat();

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error!</p>;

  return (
    <div>
      <button onClick={() => setPage((p) => p + 1)}>加载更多</button>
      {/* 复用之前的正常遍历逻辑 */}
      {allRuleSets?.length ? (
        allRuleSets.map((ruleSet: RuleSetType) => (
          <div key={ruleSet._id}>
            <RuleSetsItem ruleSets={ruleSet} />
          </div>
        ))
      ) : (
        <p>暂无规则集数据</p>
      )}
    </div>
  );
}

报错原因说明

之前的写法存在3个问题:

  • 没有为接口返回值加空值兜底,首次渲染时接口返回的data为undefined,存入dataPerPage后调用p.map直接抛出异常
  • 遍历p时没有给RuleSetsItem传递ruleSets属性,也没有指定唯一key
  • 没有过滤掉dataPerPage中的无效空值项

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:36:03