使用useEffect Hooks时首页数据未渲染是什么原因导致的?
React useEffect调用接口获取宝可梦数据未渲染问题修复方案
问题根因
- 初始状态判断逻辑错误:你定义的
pokemonData初始值为空数组[],JavaScript中空数组属于布尔真值,所以三元判断pokemonData ? xxx : loading会直接执行map逻辑,请求未返回时数组为空自然没有内容渲染,不会触发你预期的加载动画。 - 列表渲染缺少唯一key属性:React使用map遍历渲染列表时,每一项必须绑定唯一key值,否则会触发控制台警告,也可能导致DOM更新异常。
- 缺少请求错误捕获逻辑:如果接口请求出现跨域、地址错误、网络异常等问题,没有catch分支处理错误,无法感知请求失败情况,状态会一直保持为空数组。
修复后代码
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([]) // 新增加载状态专门管理加载逻辑 const [loading, setLoading] = useState(true) useEffect(() => { axios.get(POKEMON_API_URL + "?limit=100").then((res) => { if (res?.data?.results) { const { results } = res.data; const newPokemonData = results.map((pokemon, index) => ({ id: index + 1, url: `${IMAGE_API_URL}${index + 1}.png`, name: pokemon.name })) setPokemonData(newPokemonData); } }).catch(err => { // 可根据业务需求添加错误提示逻辑 console.error("宝可梦数据请求失败:", err) }).finally(() => { setLoading(false) }) },[]) return ( <Box> {loading ? <CircularProgress style={{marginTop:100}} /> : pokemonData.map((pokemon)=>( <h1 key={pokemon.id}>{pokemon.name}</h1> )) } </Box> ) } export default Pokedex;
内容的提问来源于stack exchange,提问作者NIKHIL MALIK
相关产品推荐
相关产品推荐

