如何在React+TypeScript项目中提取Rapid API返回数组中的JSON对象
实现方案
步骤1:规范接口定义(可选,符合TS命名规范)
将原接口调整为大驼峰命名,更符合TypeScript开发惯例:
interface Club { id: string, name: string, image: string }
你也可以保留原clubObjects命名,不影响功能使用。
步骤2:在组件内实现请求+数据提取
你需要把请求逻辑放在useEffect钩子中避免重复触发,请求成功后遍历返回的数组,映射出符合你接口结构的字段即可,完整实现代码如下:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; // 自定义接口 interface Club { id: string, name: string, image: string } const ClubList: React.FC = () => { // 声明state存储处理后的俱乐部数据 const [clubs, setClubs] = useState<Club[]>([]); useEffect(() => { const options = { method: 'GET', url: 'https://transfermarket.p.rapidapi.com/clubs/list-by-competition', params: {id: 'ES1'}, headers: { 'x-rapidapi-host': 'transfermarket.p.rapidapi.com', 'x-rapidapi-key': 'mykey' } } axios.request(options).then(function (response) { // 注意:请根据控制台打印的实际返回结构调整数组路径 // 示例默认返回结构为response.data.clubs是俱乐部数组,若你返回的根就是数组可直接用response.data const rawClubList = response.data.clubs || response.data; // 遍历映射提取需要的字段,得到符合Club接口的数组 const formattedClubs: Club[] = rawClubList.map((rawItem: any) => { return { id: rawItem.id, name: rawItem.name, // 若返回的图片字段名不是image,比如是logo、imageUrl请对应调整 image: rawItem.image } }); // 存入state即可在组件内使用 setClubs(formattedClubs); }).catch(function (error) { console.error(error); }); }, []); // 空依赖表示组件挂载时仅执行一次 // 渲染示例 return ( <div> {clubs.map(club => ( <div key={club.id}> <img src={club.image} alt={club.name} /> <p>{club.name}</p> </div> ))} </div> ) } export default ClubList;
可选:增加类型校验避免字段缺失报错
如果需要更严谨的校验,过滤掉返回数据中缺少id/name/image字段的无效项,可以增加类型守卫:
const isClub = (item: any): item is Club => { return typeof item.id === 'string' && typeof item.name === 'string' && typeof item.image === 'string'; } // 在映射后增加过滤 const formattedClubs: Club[] = rawClubList.map((rawItem: any) => ({ id: rawItem.id, name: rawItem.name, image: rawItem.image })).filter(isClub);
内容的提问来源于stack exchange,提问作者Hoàng Tuấn Đoàn
相关产品推荐
相关产品推荐

