我自己学习 react 和 js。请解释为什么会出现这种情况。PS:请原谅我的大文本,我试图尽可能清楚地解释问题。谢谢。事情的本质:通过钩子设置初始状态:
const [pokemon, setPokemon] = useState({
img: "",
name: "",
types: [],
abilities: [],
moveList: [],
weight: "",
height: "",
description: "",
genus: "",
chanceToCatch: "",
evolutionURL: ""
});
此外,我发出 api 请求以从 useEffect 内部获取信息:
useEffect(() => {
const fetchData = async () => {
await Axios({
method: "GET",
url: urlPokemonAPI
})
.then(result => {
const pokemonResponse = result.data;
/* Pokemon Information */
const img = pokemonResponse.sprites.front_default;
const name = pokemonResponse.name;
const weight = Math.round(pokemonResponse.weight / 10);
const height = pokemonResponse.height / 10;
const types = pokemonResponse.types.map(type => type.type.name);
const abilities = pokemonResponse.abilities.map(
ability => ability.ability.name
);
const moveList = pokemonResponse.moves.map(move => move.move.name);
setPokemon(() => {
return {
img: img,
name: name,
weight: weight,
types: types,
abilities: abilities,
moveList: moveList,
height: height
};
});
})
问题特别出现eggGroups(具有相同的处理abilities并且types没有这样的问题)。这就是当我想<div> Egg Group: {pokemon.eggGroups} </div>在数据正常显示时将数据输出到页面时发生的情况,但只要我想输出eggGroups以及abilities用types逗号(join ( ','))分隔 - 错误:TypeError: pokemon.eggGroups is undefined。我决定通过控制台检查这件事,并将这个eggGroups密钥塞进超时:

在某些时候,eggGroups变得未定义......为什么,我无法理解。但是如果我单独设置状态,const [egg, setEgg] = useState ([]); setEgg (eggGroups);就不会观察到这样的问题。为什么会这样?一切都很好types和abilities。先感谢您。
慕神8447489
泛舟湖上清波郎朗
犯罪嫌疑人X
随时随地看视频慕课网APP
相关分类