反应提取多个获取请求
是否有一种更简单或有条不紊的方法来获取多个请求而无需使用循环?我基本上想获取有关所有Kanto Pokemon(151个口袋妖怪)的所有信息,然后在获取所有151个请求后,仅提取口袋妖怪的名称和前链列表,并使用新的填充阵列更新我的状态。我正在考虑使用Promise.All。但是后来我无法跟踪每个口袋妖怪的柜台。
const [pokemondata,setPokemondata] = useState([]);
useEffect(() => {
const pokemon = []
for (let i = 1;i < 152; i++) {
fetch(`https://pokeapi.co/api/v2/pokemon-form/${i}`)
.then((response) => {
return response.json()
})
.then((data) => {
pokemon.push({name: data.name,sprite: data.sprites.front_default})
})
}
setPokemondata(pokemon)
},[])
Is there a simpler or more methodical way of fetching multiple requests without having to use a for loop? I basically want to fetch all the information regarding all the Kanto pokemon (151 pokemon), and then extract just the name and front sprite of the pokemon updating my state with the new populated array after fetching all 151 requests. I'm considering doing so using Promise.all but then I have no way of keeping track of the counter for every pokemon.
const [pokemondata,setPokemondata] = useState([]);
useEffect(() => {
const pokemon = []
for (let i = 1;i < 152; i++) {
fetch(`https://pokeapi.co/api/v2/pokemon-form/${i}`)
.then((response) => {
return response.json()
})
.then((data) => {
pokemon.push({name: data.name,sprite: data.sprites.front_default})
})
}
setPokemondata(pokemon)
},[])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建一系列承诺。我已经使用了
array.from()
,但是您也可以使用循环并将承诺推到数组。然后使用Promise.all()
等待所有承诺,并在准备就绪时设置状态:Create an array of promises. I've used
Array.from()
, but you can also use a for loop and push the promises to an array. Then usePromise.all()
to wait for all promises, and set the state when it's ready: