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

使用PokeAPI构建宝可梦图鉴时无法访问对象属性的问题

问题描述

我正在使用PokeAPI构建一个小型宝可梦图鉴,从接口获取数据并构建自定义对象。页面加载时执行的构建函数如下:

$: pokemon = []

//fetch pokemon from PokeAPI
function getPokemon(){
let index = 0

fetch("https://pokeapi.co/api/v2/pokemon?limit=151")
    .then(response => response.json())
    .then(allpokemon =>  {
    allpokemon.results.map((poke) => 
    
        pokemon = [...pokemon, {
            index: index++,
            name: poke.name
        }]
    )})
}   

//populate pokemon array on page load
getPokemon()

我可以在控制台打印该对象并在开发者工具中查看,也能将其JSON序列化后在HTML中展示。但每当尝试获取特定属性时,会出现500错误。例如,我尝试在h1标签中显示当前宝可梦的名称:

<h1>{pokemon[currentPokemon].name}</h1> <!-- 无法正常工作 -->

这无法正常工作,而

<h1>{pokemon[currentPokemon]}</h1> <!-- 可以正常显示 -->

可以正常显示。这应该是个简单的修复,但我不清楚问题所在,我认为自己一直以来的对象遍历方式是正确的,恳请帮助。

解决方案

核心问题是异步加载的时序问题:页面渲染时pokemon数组还没被API返回的数据填充,此时pokemon[currentPokemon]是undefined,尝试访问undefined.name就会抛出错误,导致500。而直接打印pokemon[currentPokemon]时,框架(从$:语法判断是Svelte)会在数组更新后自动重新渲染,所以能显示出对象内容。

具体修复方案:

  • 添加空值保护
    使用可选链操作符?.避免访问undefined的属性,这样既不会报错,数据加载完成后会自动显示名称:

    <h1>{pokemon[currentPokemon]?.name}</h1>
    
  • 优化数组更新逻辑
    当前用map遍历的方式每次都展开数组重新赋值,效率低下,直接用map生成完整的新数组再赋值:

    function getPokemon(){
        fetch("https://pokeapi.co/api/v2/pokemon?limit=151")
            .then(response => response.json())
            .then(allpokemon =>  {
                pokemon = allpokemon.results.map((poke, idx) => ({
                    index: idx,
                    name: poke.name
                }))
            })
    }
    

    一次赋值完成数组更新,响应式系统能更高效触发重新渲染。

  • 添加加载状态提示
    可以在数据加载完成前显示加载提示,避免页面出现空白或错误:

    {#if pokemon.length === 0}
        <p>加载中...</p>
    {:else}
        <h1>{pokemon[currentPokemon].name}</h1>
    {/if}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:45:49