【发布时间】:2020-04-21 19:02:17
【问题描述】:
因此,我正在使用的 API 没有一个来源来获取所有口袋妖怪,但它具有指向每个来源的链接,其 id 作为参数。我正在使用 for 循环来获取所有请求。我使用异步等待同步执行此操作,但它真的很慢。
代码不工作。它正在收到请求,但没有正确更新地图。它只在收到请求之前记录当前地图。
import React from 'react'
import axios from 'axios'
//Defines what a Pokemon has
interface Pokemon {
name: string,
id: number,
sprite: string
}
const PokemonList2: React.FC<{}> = (props) => {
//The state is a Map of pokemon. Key is the Pokemon's name, value is a Pokemon object
const [pokemonMap, setPokemonMap] = React.useState<Map<string, Pokemon>>(new Map<string, Pokemon>())
//Handles API request
React.useEffect(() => {
//Sets the temporary map equal to the state's map
let tempPokemonMap: Map<string, Pokemon> = pokemonMap
//loops through pokemon
for (let i = 1; i <= 50; i++){
//says it's loading
console.log('loading...')
//gets the request
axios.get('https://pokeapi.co/api/v2/pokemon/' + i)
.then(res => {
//adds the new pokemon to the map
tempPokemonMap.set(res.data.name, {
name: res.data.name,
id: res.data.id,
sprite: res.data.sprites.front_default
})
//Sets the state map to the temp map
setPokemonMap(tempPokemonMap)
//logs that is was added
console.log(`Added ${ res.data.id } : ${ res.data.name }`)
})
}
}, [setPokemonMap, pokemonMap])
//logs the current map
console.log(pokemonMap)
//Gets JSX from the map
let pokemonJSX: JSX.Element[] = []
pokemonMap.forEach(pok => {
pokemonJSX.push(
<div key={ pok.id } style={{ textAlign: "center" }}>
<p>{ pok.name }</p>
<img src={ pok.sprite } alt={ pok.name }/>
</div>
)
})
//Prints the JSX
return (
<div className="container">
{ pokemonJSX }
</div>
)
}
export default PokemonList2
【问题讨论】:
-
不要在 for 循环中执行多个请求。改为这样做:stackoverflow.com/questions/52669596/promise-all-with-axios
标签: javascript reactjs typescript axios