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

React获取嵌套API数据渲染UI时出现map读取undefined报错

解决React读取嵌套JSON数组时的"Cannot read properties of undefined (reading 'map')"错误

问题重现

你尝试通过fetch获取NCAA橄榄球新闻API数据,存入React的UI state后渲染嵌套的rel数组时触发错误,错误提示为Cannot read properties of undefined (reading 'map')。你的代码如下:

异步请求函数

async function get() {
    let get = await fetch("http://site.api.espn.com/apis/site/v2/sports/football/college-football/news");
    let result = await get.json();
    return result;
}

React组件代码

export default function App() {
    const [UI, setUI] = useState([]);
    useEffect(() => {
        get().then((final) => {
            setUI(final);
        })
    })
    return (
        <>
        {UI.rel.map(result => <p>{result}</p>)}
        </>
    )
}

错误原因

  1. 初始state类型不匹配:你把UI初始化为数组[],但API返回的是对象,数组不存在rel属性,初始渲染时UI.rel直接为undefined,调用map自然报错。
  2. 嵌套路径访问错误:API返回的rel数组嵌套在link对象下,而非根节点,正确路径应为UI.link.rel而非UI.rel。
  3. useEffect无限循环:缺少依赖数组,会导致组件每次渲染都重复调用fetch。

修复方案

  1. 修正初始state:将UI初始化为匹配API返回结构的对象,确保初始状态下访问嵌套属性不会触发undefined。
  2. 使用可选链操作符:通过?.安全访问嵌套属性,避免因数据未加载完成导致的报错。
  3. 添加useEffect依赖数组:传入空数组[],确保fetch仅在组件挂载时执行一次。
  4. 修正数组访问路径:改为访问UI?.link?.rel。

完整修复代码

import { useState, useEffect } from 'react';

async function get() {
    let response = await fetch("http://site.api.espn.com/apis/site/v2/sports/football/college-football/news");
    let result = await response.json();
    return result;
}

export default function App() {
    // 初始化为匹配API返回结构的对象
    const [UI, setUI] = useState({ link: { rel: [] } });
    
    useEffect(() => {
        get().then((final) => {
            setUI(final);
        });
    }, []); // 添加空依赖数组
    
    return (
        <>
            {/* 使用可选链安全访问嵌套数组,添加key属性符合React规范 */}
            {UI?.link?.rel.map((item, index) => (
                <p key={index}>{item}</p>
            ))}
        </>
    )
}

额外说明

  • 给map生成的元素添加key属性,避免React列表渲染警告。
  • 若使用React 16.8以下版本,可选链操作符?.不支持,可改用条件判断替代:UI.link && UI.link.rel && UI.link.rel.map(...)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 01:03:35