“以对象类型的键获取的数据未定义?”

huangapple go评论75阅读模式
英文:

Fetched data with key of type objects are undefined?

问题

I try to learn a bit about fetching from APIs but have a hard time.
Can someone explain me, why the pokemon['name'] is undefined,
but pokemon['name'] works just fine?

import React, { useState } from "react";

export default function Mybutton() {
    const [pokemon, setPokemon] = useState("");

    const getPokemon = () => {
      fetch("https://pokeapi.co/api/v2/pokemon/4/").then(
        (response) => response.json())
        .then((data) => {
          setPokemon(data);
        });
    };

    return (
      <div>
        <button onClick={getPokemon}>Get pOKIMON</button>
        {pokemon['name']}
        {pokemon.sprites['back_default']}
      </div>
    );
  }

I tried to Google the problem, but I don't know, what exactly I am looking for!

英文:

I try to learn a bit about fetching from APIs but have a hard time.
Can someone explain me, why the pokemon[&#39;sprites&#39;][&#39;back_default&#39;] is undefined,
but pokemon[&#39;name&#39;] works just fine?

import React, { useState } from &quot;react&quot;;

export default function Mybutton() {
    const [pokemon, setPokemon] = useState(&quot;&quot;);

    const getPokemon = () =&gt; {
      fetch(&quot;https://pokeapi.co/api/v2/pokemon/4/&quot;).then(
        (response) =&gt; response.json())
        .then((data) =&gt; {
          setPokemon(data);
        });
    };

    return (
      &lt;div&gt;
        &lt;button onClick={getPokemon}&gt;Get pOKIMON&lt;/button&gt;
        {pokemon[&#39;name&#39;]}
        {pokemon.sprites[0].back_default}
      &lt;/div&gt;
    );
  }
  

I tried to Google the problem, but I don't know, what exactly I am looking for!

答案1

得分: 1

When react tries to render the component initially, the pokemon variable holds nothing, hence it throws an error. So you have to check if the variable is empty or not.

{pokemon && pokemon['name']} // 检查 pokemon 是否为空
{pokemon && pokemon.sprites[0]?.back_default} // 检查 pokemon 和 sprites[0] 是否存在

also, you can define the state variable as empty since you don't intend to store a string in it.

const [pokemon, setPokemon] = useState();

英文:

When react tries to render the component initially pokemon variable holds nothing. hence it throws an error. So you have to check if the variable is empty or not.

{pokemon &amp;&amp; pokemon[&#39;name&#39;]} //check if pokemon is empty
{pokemon &amp;&amp; pokemon.sprites[0]?.back_default} // check if pokemon and sprites[0] exists

also, you can define the state variable as empty since you dont intend to store a string in it.

    const [pokemon, setPokemon] = useState();

huangapple
  • 本文由 发表于 2023年7月3日 02:52:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定