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

如何通过Fetch获取API多页数据以获取全部球员信息?

获取balldontlie API全部球员数据的解决方案

要获取所有3828名球员数据,你需要遍历所有分页请求,合并各页结果后再分发到Redux。以下是修改后的代码:

const getPlayers = async () => {
  // 先获取第一页数据,拿到总页数
  const firstPageRes = await fetch(`https://www.balldontlie.io/api/v1/players?per_page=100`);
  const firstPageData = await firstPageRes.json();
  const totalPages = firstPageData.meta.total_pages;

  // 生成所有页面的请求Promise
  const pagePromises = [];
  // 遍历所有页码,创建请求
  for (let page = 1; page <= totalPages; page++) {
    pagePromises.push(
      fetch(`https://www.balldontlie.io/api/v1/players?per_page=100&page=${page}`)
        .then(res => res.json())
        .then(data => data.data) // 只保留每一页的球员数据数组
    );
  }

  // 等待所有请求完成,合并所有球员数据
  const allPlayers = (await Promise.all(pagePromises)).flat();

  // 分发合并后的全部球员数据
  dispatch(playerActions.getPlayers({ data: allPlayers, meta: firstPageData.meta }));
};

关键说明:

  • 使用async/await简化异步流程,避免多层回调嵌套
  • 先请求第一页拿到总页数,确定需要遍历的页码范围
  • 通过Promise.all并行发起所有分页请求,提升效率(balldontlie免费API速率限制为每分钟60次,39页请求量在限制内)
  • 用flat()方法将多页的球员数组合并成一个完整数组
  • 分发时可带上原meta信息,或根据需求调整结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 04:30:56