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

React调用API获取对象数组后执行map操作报错如何解决

错误原因

  • 初始state类型不匹配:你调用的API返回结果是数组,Attempt1、3将getBirds初始值设为对象,而对象不存在map方法,首次渲染时接口数据还未返回,会直接触发xxx.map is not a function报错。
  • map方法使用不符合规范:数组的map方法要求传入回调函数处理每一项元素,你直接写getBirds.map(image)属于错误用法;同时map返回值是新数组,不能直接赋值给img标签的src、alt属性,这两个属性要求传入字符串类型的值。
  • 加载状态判断逻辑错误:空数组的布尔值为true,你写的if (!getBirds)判断永远不会命中接口未返回的空数组场景,会直接执行后续渲染逻辑,进一步触发报错。
  • 数据使用逻辑混乱:你解构了props里的image变量,但实际要渲染的是接口返回的鸟类数据自带的图片字段,这个props参数完全不需要,把它传入map的逻辑也不成立。

修正后的可运行代码

import { useState, useEffect } from 'react'
import axios from 'axios'

function Birds() {
   // 初始值设为空数组,匹配接口返回类型
   const [getBirds, setGetBirds] = useState([])
   const [loading, setLoading] = useState(true)

   useEffect(() => {
      async function fetchBirds() {
         const URL = `https://audubon-society-api.herokuapp.com/birds`
         try {
            const res = await axios.get(URL)
            setGetBirds(res.data)
         } catch (error) {
            console.log(error)
         } finally {
            setLoading(false)
         }
      }
      fetchBirds()
   }, [])
   
   if (loading) return <h3>Loading...</h3>

   return (
      <div>
         {/* 遍历数组,每个鸟数据对应一个img标签,取数组项里的img字段作为地址,name字段作为alt文本 */}
         {getBirds.map(bird => (
            <img key={bird.id} src={bird.img} alt={bird.name} />
         ))}
      </div>
   )
}

export default Birds

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:54:02