React中数组数据表格渲染问题求助
解决React渲染人口普查API数据到表格的问题
你的核心问题是没搞清楚美国人口普查API返回的数据结构——它返回的是二维数组,第一行是字段名,后续行是对应的数据值,不是你想的对象数组。所以直接用item.POP_2021这种对象属性访问方式会取不到值,自然渲染不出来。
下面是具体的修改步骤和完整代码:
关键修改点
- 处理API返回数据:跳过第一行的表头,只取实际数据行;
- 数组索引访问数据:因为每个数据项是数组,用索引
item[0]、item[1]等获取对应字段值; - 替换唯一key:用州编号
item[3]作为key,避免重复; - 移除无效的
import Table from 'react'语句; - 正确放置
console.log:要包裹在JSX的{}中才能执行。
修改后的完整代码
import logo from './logo.svg'; import './App.css'; import React, { useEffect, useState } from "react"; function App() { const [error, setError] = useState(null); const [isLoaded, setIsLoaded] = useState(false); const [items, setItems] = useState([]); useEffect(() => { fetch("https://api.census.gov/data/2021/pep/population?get=DENSITY_2021,POP_2021,NAME,STATE&for=state:*") .then(res => res.json()) .then( (result) => { setIsLoaded(true); // 跳过第一行表头,只保留数据行 setItems(result.slice(1)); }, (error) => { setIsLoaded(true); setError(error); } ) }, []) if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return( <table border="1"> {/* 加border方便查看表格结构 */} <thead> <tr> <th>Population Density</th> <th>Population</th> <th>State</th> </tr> </thead> <tbody> {console.log(items)} {items.map(item => ( <tr key={item[3]}> {/* 用州编号作为唯一key */} <td>{item[0]}</td> {/* DENSITY_2021 */} <td>{item[1]}</td> {/* POP_2021 */} <td>{item[2]}</td> {/* NAME */} </tr> ))} </tbody> </table> ); } } export default App;
额外优化(可选)
如果你习惯用对象访问的方式,可以把数据行转成对象数组,比如在setItems的时候处理:
const headers = result[0]; const dataRows = result.slice(1).map(row => { return headers.reduce((obj, key, index) => { obj[key] = row[index]; return obj; }, {}); }); setItems(dataRows);
这样之后你就可以用item.DENSITY_2021、item.POP_2021这种方式访问,map的时候key用item.STATE即可。
内容的提问来源于stack exchange,提问作者2000rs25
相关产品推荐
相关产品推荐

