首页 > 解决方案 > React:无法获取多个获取请求

问题描述

因此,我正在使用的 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

标签: javascriptreactjstypescriptaxios

解决方案


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

此外,我还建议正如 d3bgger 提到的那样,您完成所有请求,然后更新状态。无论是性能还是用户体验。


推荐阅读