gpt4 book ai didi

javascript - 如何在 pokeAPI 中获取有关神奇​​宝贝的详细信息

转载 作者:行者123 更新时间:2023-12-05 06:19:00 28 4
gpt4 key购买 nike

最近开始学习react。我正在使用 pokeAPI 制作一个图鉴应用程序。在卡片上,我需要获取每个口袋妖怪的类型。下面是我如何获取和保存口袋妖怪数据的示例。

 useEffect(() => {
const endpointForPokemonInfo = `${pokemonUrl}`;
fetchPokemon(endpointForPokemonInfo); // eslint-disable-next-line
}, []);

const fetchPokemon = endpointForPokemonInfo => {
fetch(endpointForPokemonInfo)
.then(result => result.json())
.then(result => {
setPokemon([...Pokemon, result.results]);
}, setLoadingForPokemon(false))
.catch(error => console.error("Error:", error));
};

这是我如何显示口袋妖怪类型的示例。

      {Pokemon &&
Pokemon.map((types, id) => (
<React.Fragment key={id}>
<div
style={{
color: "#333",
padding: 5,
maxWidth: 100,
display: "inline-block"
}}
>
{types.type.name}
</div>
</React.Fragment>
))}

我不知道是什么问题,但它会抛出一个错误。

Uncaught TypeError: Cannot read property 'type' of undefined
at GridCards.js:50
at Array.map (<anonymous>)
at GridCards (GridCards.js:46)
at renderWithHooks (react-dom.development.js:14803)
at updateFunctionComponent (react-dom.development.js:17034)
at beginWork (react-dom.development.js:18610)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at beginWork$1 (react-dom.development.js:23203)
at performUnitOfWork (react-dom.development.js:22154)
at workLoopSync (react-dom.development.js:22130)
at performSyncWorkOnRoot (react-dom.development.js:21756)
at react-dom.development.js:11089
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
at flushSyncCallbackQueue (react-dom.development.js:11072)
at scheduleUpdateOnFiber (react-dom.development.js:21199)
at dispatchAction (react-dom.development.js:15660)
at GridCards.js:23

如果我 console.log(result)console.log(...Pokemon),控制台会显示此结果

console.log(result)

最佳答案

从结果结构可以看出Pokemon.types也是一个数组,所以需要再次使用.map():

{ 
Pokemon &&
Pokemon.map((types, id) => (
<React.Fragment key={id}>
{
types.map((currType, typeId) => (
<div
key={typeId}
style={{
color: "#333",
padding: 5,
maxWidth: 100,
display: "inline-block"
}}
>
{currType.type.name}
</div>
))
}
</React.Fragment>
))
}

关于javascript - 如何在 pokeAPI 中获取有关神奇​​宝贝的详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61034812/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com