英文:
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['sprites']['back_default']
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[0].back_default}
</div>
);
}
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 && pokemon['name']} //check if pokemon is empty
{pokemon && 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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论