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

React获取嵌套对象报错:Cannot read properties of undefined (reading 'map')

问题解决:React中访问Pokémon API数据时的map报错

错误原因

  1. 初始状态不匹配:你把pokemon的初始useState设为数组[],但API返回的是单个对象而非数组。首次渲染时pokemon.types不存在,调用map直接触发错误。
  2. 异步数据未做加载判断:API请求是异步的,组件首次渲染时还没拿到数据,此时pokemon.types为undefined,直接调用map会抛出类型错误。

修复方案

步骤1:修正初始状态

将pokemon的初始值改为空对象{},匹配API返回的数据结构:

const [pokemon, setPokemon] = useState({})

步骤2:安全访问嵌套属性

在调用map或访问嵌套属性前,添加判断避免undefined报错,两种常用方式:

方式1:可选链操作符(推荐)

用?.安全访问嵌套属性,配合??设置默认值:

const pokemonType = pokemon.types ?? []
// 直接调用map时也可用可选链
pokemon.types?.map(x => console.log(x.type.name))

方式2:条件判断

在执行map前先检查数据是否存在:

if (pokemon.types) {
  pokemon.types.map(x => console.log(x.type.name))
}

完整修复代码

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

function PokemonCard() {
  // 初始值改为空对象
  const [pokemon, setPokemon] = useState({})
  
  useEffect(() => {
    fetch('https://pokeapi.co/api/v2/pokemon/charizard')
      .then(res => res.json())
      .then(setPokemon)
      .catch(err => console.error('请求失败:', err))
  },[])

  // 给类型数组设置默认空数组,避免map报错
  const pokemonType = pokemon.types ?? []
  pokemonType.map(x => console.log(x.type.name))

  return (
    <div>
      {/* 首次渲染时显示加载提示 */}
      <h1>{pokemon.name ?? 'Loading...'}</h1>
      <img src={pokemon.sprites?.front_default} alt={pokemon.name || 'Pokémon'} />
      {/* 渲染类型,用逗号分隔 */}
      <h2>Type: {pokemonType.map(type => type.type.name).join(', ')}</h2>
      <h2>Height: {pokemon.height ?? '-'}</h2>
      <h2>Weight: {pokemon.weight ?? '-'}</h2>
    </div>
  )
}

export default PokemonCard;

额外提示

  • 可添加加载状态提示,提升用户体验;
  • 记得捕获API请求失败的情况,避免控制台报错无处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 13:24:48