反应:无法获取多个提取请求

时间:2020-04-21 19:02:17

标签: javascript reactjs typescript axios

因此,我正在使用的API没有获取所有Pokemon的来源,但是它具有指向每个ID的链接,并以其id作为参数。我正在使用for循环来获取所有请求。我使用async await同步进行了此操作,但这确实很慢。

代码不起作用。它正在获取请求,但未正确更新地图。它只会在获取请求之前记录当前地图。

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

1 个答案:

答案 0 :(得分:0)

在这种情况下,您的问题是,当您将tempPokemonMap分配为pokemonMap时,您实际上并没有将pokemonMap的值复制到变量中,而只是传递了引用。稍后当您尝试更新状态时,会将相同的引用传递给已处于状态的对象,这就是为什么React无法检测到任何更改以及为何不重新呈现的原因。

此外,正如d3bgger所提到的,我还建议您执行所有请求,然后更新状态。在性能和用户体验方面。