繁体   English   中英

无法显示 object 属性

[英]Having trouble displaying object property

我正在使用 PokeAPI 构建一个小型图鉴。 我正在从端点检索数据并构建自己的 object。我为后者构建的 function 在页面加载时运行,如下所示:

$: 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()

我能够控制台记录 object 并在 devtools 中遍历它,还能够将 JSON 字符串化并显示在 html 内。但是每当我尝试检索特定属性时,我都会收到 500 错误。 例如,我试图在 h1 标签中显示当前的宠物小精灵名称

<h1>{pokemon[currentPokemon].name</h1> // this doesn't work

然而

<h1>{pokemon[currentPokemon]</h1> //this does

这不能太复杂的修复,我只是不知道我错过了什么,因为多年来我一直在遍历对象,我认为这是正确的方法。 谢谢你。

此行末尾缺少大括号

<h1>{pokemon[currentPokemon].name</h1>

除了pokemon最初是一个空数组,因此独立于currentPokemon的值将是undefined的并且访问键name给出错误Cannot read properties of undefined (reading 'name')这可以通过添加问号来解决(可选链接)

<h1>{pokemon[currentPokemon]?.name}</h1>

不需要$: ,只需let pokemon = []
.map()返回一个数组,因此与其在 function 中设置pokemon ,不如将结果分配给它。 该索引将作为.map()中的第二个参数提供

.then(allpokemon =>  {
            pokemon = allpokemon.results.map((poke, index) => {
                return {
                    name: poke.name, // or ...poke, to keep all fields
                    index
                }
            })

如果使用#each循环显示数据,则可能不需要在数据中写入索引

{#each pokemon as p, index}
    <p>
        {index} - {p.name}
    </p>
{/each}

尝试这个:-

<h1>{pokemon[currentPokemon]['name']}</h1>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM