如何在React.js中展示API返回的嵌套对象数组数据?
解决React中API数据格式化展示的方案
第一步:分析并处理API返回的数据结构
你的API返回的是二维嵌套数组,每个子数组里包含一个仅含单个键值对的对象。我们需要先把这个结构扁平化,再提取出每个键和对应的值:
// 假设API返回的数据是这个变量 const rawApiData = [[{"AG":2707}],[{"AR":398}],[{"AI":28}],[{"BL":1085}],[{"BS":1318}],[{"BE":2964}],[{"GL":206}],[{"GR":845}],[{"JR":256}],[{"LU":1855}],[{"NW":297}],[{"OW":307}],[{"SH":307}],[{"SZ":1118}],[{"SO":945}],[{"SG":2029}],[{"TI":2146}],[{"TG":1038}],[{"UR":107}],[{"VS":1237}],[{"ZG":3714}],[{"ZH":8496}]]; // 1. 扁平化二维数组,得到一维对象数组 const flattenedData = rawApiData.flat(); // 2. 转换为[{ key: 'AG', value: 2707 }, ...]格式的数组 const formattedData = flattenedData.map(item => { // 提取对象的第一个键值对(因为每个对象只有一组数据) const [key, value] = Object.entries(item)[0]; return { key, value }; });
第二步:在React组件中渲染格式化后的数据
用函数组件结合useState和useEffect实现数据请求与渲染,完整示例如下:
import { useState, useEffect } from 'react'; function DataDisplay() { const [formattedData, setFormattedData] = useState([]); useEffect(() => { // 发起API请求(实际项目替换为你的真实API地址) const fetchAndProcessData = async () => { try { const response = await fetch('你的API接口地址'); const rawData = await response.json(); // 处理数据 const flattened = rawData.flat(); const processed = flattened.map(item => { const [key, value] = Object.entries(item)[0]; return { key, value }; }); setFormattedData(processed); } catch (error) { console.error('数据请求失败:', error); } }; fetchAndProcessData(); }, []); return ( <div style={{ padding: '1rem' }}> {formattedData.map((item, index) => ( <div key={index} style={{ marginBottom: '0.5rem' }}> <code>{item.key} : {item.value}</code> </div> ))} </div> ); } export default DataDisplay;
可选优化:直接在渲染时处理数据(简化代码)
如果不需要保存格式化后的数据到状态,也可以在渲染阶段直接处理原始数据,减少状态变量:
// 仅修改渲染部分 return ( <div style={{ padding: '1rem' }}> {rawApiData.flat().map((item, index) => { const [key, value] = Object.entries(item)[0]; return ( <div key={index} style={{ marginBottom: '0.5rem' }}> <code>{key} : {value}</code> </div> ); })} </div> );
注意事项
- 渲染列表时必须给每个元素添加唯一
key属性,示例中用index是临时方案,如果API返回的数据有唯一标识(比如键本身就是唯一的),可以用item.key作为key更合适。 - 可以添加异常处理逻辑,比如判断API返回的数据格式是否符合预期,避免因数据异常导致组件崩溃:
const processed = flattened.map(item => { if (typeof item === 'object' && item !== null && Object.keys(item).length > 0) { const [key, value] = Object.entries(item)[0]; return { key, value }; } return { key: '无效字段', value: '无效数据' }; });
内容的提问来源于stack exchange,提问作者Leo
相关产品推荐
相关产品推荐

