You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用中.map方法失效:无法处理API返回对象

问题分析与解决方案

核心问题

你的代码无法调用.map是因为API返回的数据结构与你定义的接口不匹配,导致你访问了不存在的属性:

  1. D&D 5e API返回的种族数组字段是results,但你在接口RazzeArray里定义的是razze,代码里也用razze.razze去访问,自然找不到数组。
  2. 每个种族对象的索引字段是index,不是你接口里的indice。

控制台能读取对象是因为控制台显示的是API返回的原始数据,而代码里用了错误的字段名,所以逻辑分支一直走到Loading...,不会执行.map。

修复步骤

1. 修正TypeScript接口定义

让接口完全匹配API返回的结构:

export interface RazzeArray {
    count: number
    results: Razza[] // 将razze改为results
}

export interface Razza {
    index: number // 将indice改为index
    name: string
    url: string
}

2. 调整组件中的数据访问逻辑

修改组件里的状态判断和.map部分,使用正确的字段名:

const BASE_URL = "https://www.dnd5eapi.co/api/races";

const ListaRazze = () => {
  const [razze, setRazze] = useState<RazzeArray>();

  useEffect(() => {
    fetch(BASE_URL)
      .then((res) => res.json())
      .then((results) => {
        console.log('result', results);
        setRazze(results);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  }, []);

  return (
     <>
      {razze && razze.results ? ( // 改为razze.results
        razze.results.map(({ index, name, url }) => { // 解构index而非indice
          return <div key={index}>{name} {url}</div>
        })
      ) : (
        <div>Loading...</div>
      )}
    </>
  );
};

export default ListaRazze;

可选方案:转换API返回字段(无需修改接口)

如果你坚持要使用自定义字段名,可以在setRazze前转换数据结构:

.then((results) => {
  const transformedData = {
    count: results.count,
    razze: results.results.map(race => ({
      indice: race.index,
      name: race.name,
      url: race.url
    }))
  };
  setRazze(transformedData);
})

这种方式下,原接口和组件里的razze.razze、indice都可以保留,但需要多一步数据转换。

内容的提问来源于stack exchange,提问作者Lorenzo Gaetani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:35:13