You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中数组在console.log可见但无法渲染?已使用useEffect钩子

问题原因及解决方案

你遇到的核心问题是没有用React状态管理团队列表:你定义的team_names是普通数组,修改它不会触发组件重新渲染。虽然控制台能打印出填充后的数组,但组件在数组为空时已经完成了首次渲染,后续数组变化不会让页面更新。

修正步骤:

1. 用useState定义状态

把普通数组替换为React状态变量,这样更新时会自动触发重渲染:

const [teamNames, setTeamNames] = useState([]);

2. 重构数据获取逻辑

不要直接修改数组,而是通过setTeamNames更新状态。同时用Promise.all并行请求所有接口,提升性能:

useEffect(() => {
  const fetchData = async () => {
    // 生成所有请求的Promise数组
    const fetchPromises = Array.from({ length: 30 }, (_, i) => 
      fetch(`http://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/teams/${i+1}?lang=en&region=us`)
        .then(res => res.json())
        .then(json => json.displayName)
    );
    // 等待所有请求完成,拿到所有队名
    const fetchedTeamNames = await Promise.all(fetchPromises);
    // 更新状态
    setTeamNames(fetchedTeamNames);
  };
  fetchData();
}, []); // 空依赖数组,确保只在组件挂载时执行一次

3. 修正列表渲染的key属性

React列表渲染需要给每个项加唯一key,避免警告并优化渲染:

{teamNames.map((team, index) => (
  <li key={index}>{team}</li>
))}

(如果队名唯一,也可以用key={team},index是兜底方案)

完整修正后的组件代码

import React, { useEffect, useState } from "react";
import { useGetTeamQuery } from "./store/teamsApi"

function TeamList(props) {
  const [teamNames, setTeamNames] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const fetchPromises = Array.from({ length: 30 }, (_, i) => 
        fetch(`http://sports.core.api.espn.com/v2/sports/football/leagues/nfl/seasons/2022/teams/${i+1}?lang=en&region=us`)
          .then(res => res.json())
          .then(json => json.displayName)
      );
      const fetchedTeamNames = await Promise.all(fetchPromises);
      setTeamNames(fetchedTeamNames);
    };
    fetchData();
  }, []);

  return (
    <div className="container">
      <h1>Team List</h1>
      <div>
        <ol>
          {teamNames.map((team, index) => (
            <li key={index}>{team}</li>
          ))}
        </ol>
      </div>
    </div>
  )
}

export default TeamList;

额外说明

  • 你之前的useEffect依赖数组填[team_names]会导致无限循环:因为每次渲染都会创建新的空数组,React认为依赖变化,会反复执行effect。
  • 并行请求比串行for循环效率高很多,30个请求同时发起,不用等前一个完成再发下一个。

内容的提问来源于stack exchange,提问作者granco20

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:35:17