【问题标题】:Why is data not rendering on home page using useEffect hooks?为什么使用 useEffect 钩子无法在主页上呈现数据?
【发布时间】:2021-11-10 06:26:03
【问题描述】:
import { Box, CircularProgress } from '@material-ui/core'
import axios from 'axios'
import React, { useEffect, useState } from 'react';
import { POKEMON_API_URL,IMAGE_API_URL} from './configs';

function Pokedex() {
    const [pokemonData,setPokemonData]=useState([])

    useEffect(() => {
        axios.get(POKEMON_API_URL + "?limit=100").then((res) => {
            if (res) {
                const { results } = res.data;
                let newPokemonData = [];
                results.forEach((pokemon, index) => {
                    index++
                    let PokemonObject = {
                        id: index,
                        url:IMAGE_API_URL+index+".png",
                        name:pokemon.name,
                    }
                    newPokemonData.push(PokemonObject);
                });
                  
                setPokemonData(newPokemonData);
            }
        })
    },[])


    return (
        <Box>
          {pokemonData ? pokemonData.map((pokemon)=>(
               <h1>{pokemon.name}</h1>
          )) : <CircularProgress style={{marginTop:100}} /> } 
        </Box>
    )
}

export default Pokedex;

   

【问题讨论】:

  • 您是否收到了有效的网络响应? .then 块中 res 的值是多少?您是否确认状态已更新?
  • 请打印 console.log(res)

标签: reactjs react-hooks


【解决方案1】:

检查这种方式是否可行,我使用了async await,这是一种更简洁的方法来避免不可调试的.then()调用地狱,还在useEffect中使用了依赖项,希望它不会是递归调用,

import { Box, CircularProgress } from '@material-ui/core'
import axios from 'axios'
import React, { useEffect, useState } from 'react';
import { POKEMON_API_URL,IMAGE_API_URL} from './configs';

function Pokedex() {
    const [pokemonData,setPokemonData]=useState([])

    useEffect(() => {

        const res = call();
        if (res) {
            const { results } = res.data;
            let newPokemonData = [];
            results.forEach((pokemon, index) => {
                index++
                let PokemonObject = {
                    id: index,
                    url:IMAGE_API_URL+index+".png",
                    name:pokemon.name,
                }
                newPokemonData.push(PokemonObject);
            });
                
            setPokemonData(newPokemonData);
        }

    },[pokemonData])

    const call = async () => {
        const data = await axios.get(POKEMON_API_URL + "?limit=100");
        const res = data.json();
        console.log(res); // check if there is any data
        return res;
    }


    return (
        <Box>
          {pokemonData ? pokemonData.map((pokemon)=>(
               <h1>{pokemon.name}</h1>
          )) : <CircularProgress style={{marginTop:100}} /> } 
        </Box>
    )
}

export default Pokedex;

【讨论】:

    猜你喜欢
    • 2018-05-07
    • 2019-04-02
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多