React中数组数据映射为表格行后无法显示,求解决方法
问题排查与修复方案
你的代码存在三个核心问题,导致数据无法正常渲染:
1. map函数未返回JSX元素
你在data.map的回调中用大括号{}包裹了表格行,但没有显式返回JSX元素,React无法识别并渲染这部分内容。
2. useEffect缺少依赖数组引发无限重渲染
当前useEffect没有传入第二个参数(依赖数组),这会导致组件每次渲染都重新发起API请求,虽然数据能成功获取,但频繁的重渲染会干扰组件的正常渲染逻辑,甚至引发性能问题。
3. API数据结构访问错误
Rest Countries API返回的数据并非直接的字符串类型:
name是包含common(通用名称)等属性的对象continents是数组(多数国家仅属于一个大洲)flag是图片URL,需要用<img>标签渲染,而非直接输出字符串
修复后的完整代码
import { useEffect, useState } from 'react'; import './App.css'; function Countries() { const [data, setData] = useState([]); useEffect(() => { fetch('https://restcountries.com/v3.1/all?fields=name,continents,population,flag') .then((resp) => resp.json()) .then((apiData) => { setData(apiData); }); }, []); // 空依赖数组:仅在组件挂载时执行一次请求 return ( <div className="app-container"> <table> <thead> <tr> <th>Name</th> <th>Continent</th> <th>Population</th> <th>Flag</th> </tr> </thead> <tbody> {data.map((country) => ( <tr key={country.name.common}> {/* 用唯一的国家名称作为key,替代index更稳定 */} <td>{country.name.common}</td> <td>{country.continents[0]}</td> <td>{country.population.toLocaleString()}</td> {/* 格式化人口数字为易读格式 */} <td><img src={country.flag} alt={`${country.name.common} flag`} width="50" /></td> </tr> ))} </tbody> </table> </div> ); } export default Countries;
内容的提问来源于stack exchange,提问作者D.Hodges
相关产品推荐
相关产品推荐

