如何通过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
相关产品推荐
相关产品推荐

