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
相关产品推荐
相关产品推荐

