나는 반응과 js를 배운다. 이 상황이 발생하는 이유를 설명하십시오. 추신 : 큰 텍스트에 대해 실례합니다. 가능한 한 명확하게 문제를 설명하려고 노력했습니다. 감사. 문제의 본질 : 후크를 통해 초기 상태 설정 :
const [pokemon, setPokemon] = useState({
img: "",
name: "",
types: [],
abilities: [],
moveList: [],
weight: "",
height: "",
description: "",
genus: "",
chanceToCatch: "",
evolutionURL: ""
});
또한 useEffect 내부에서 정보를 얻기 위해 API 요청을합니다.
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
};
});
})
await Axios({
method: "GET",
url: urlPokemonSpecies
}).then(result => {
let description = "";
result.data.flavor_text_entries.forEach(flavor => {
if (flavor.language.name === "en") {
description = flavor.flavor_text;
}
});
let genus = "";
result.data.genera.forEach(genera => {
if (genera.language.name === "en") {
genus = genera.genus;
}
});
const evolutionURL = result.data.evolution_chain.url;
const eggGroups = result.data.egg_groups.map(
egg_group => egg_group.name
);
const chanceToCatch = Math.round(
(result.data.capture_rate * 100) / 255
);
setPokemon(pokemon => {
return {
...pokemon,
description: description,
genus: genus,
chanceToCatch: chanceToCatch,
evolutionURL: evolutionURL,
eggGroups: eggGroups
};
});
});
};
fetchData();
}, [urlPokemonAPI, urlPokemonSpecies]);
문제는 특별히 발생 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
. 미리 감사드립니다.
후크의 상태 업데이트 프로그램은 상태를 업데이트 할 때 상태 값을 병합하지 않고 대신 이전 값을 새 값으로 바꿉니다.
상태 업데이트 프로그램을 사용하기 때문에
setPokemon(() => {
return {
img: img,
name: name,
weight: weight,
types: types,
abilities: abilities,
moveList: moveList,
height: height
};
});
eggGroups
속성이 손실되어 정의되지 않습니다. 콜백에서 얻은 이전 상태 값을 분산하여 업데이트해야합니다.
setPokemon((prev) => {
return {
...prev
img: img,
name: name,
weight: weight,
types: types,
abilities: abilities,
moveList: moveList,
height: height
};
});
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다