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

React获取英雄联盟英雄数据报错,寻求技术帮助

问题分析与修复方案

你的代码报错核心原因是:data.data是键值对对象,而非数组,但你尝试用数组的map方法遍历它,导致champions.map is not a function错误。

修复方案一:将对象转换为数组(最直接适配原代码逻辑)

把data.data这个对象转换成英雄信息数组,再存入状态,之后即可正常使用map遍历:

const Heroes = () => {
  const [champions, setChampions] = useState([]);

  useEffect(() => {
    const getHeroes = async () => {
      try {
        const res = await fetch(
          "https://ddragon.leagueoflegends.com/cdn/12.23.1/data/en_US/champion.json"
        );
        const data = await res.json();
        // 将对象转换为英雄对象数组
        const championsArray = Object.values(data.data);
        setChampions(championsArray);
      } catch (error) {
        console.log(error);
      }
    };
    getHeroes();
  }, []);

  return (
    <div>
      {/* 注意添加唯一key属性,符合React列表渲染要求 */}
      {champions.map((champion) => (
        <p key={champion.key}>{champion.name}</p>
      ))}
    </div>
  );
};

修复方案二:直接遍历对象(需保留英雄ID时使用)

如果需要用到英雄的ID(比如Aatrox这类标识),可以用Object.entries将对象转成[英雄ID, 英雄信息]的数组后遍历:

const Heroes = () => {
  // 初始状态改为空对象,匹配data.data的类型
  const [champions, setChampions] = useState({});

  useEffect(() => {
    const getHeroes = async () => {
      try {
        const res = await fetch(
          "https://ddragon.leagueoflegends.com/cdn/12.23.1/data/en_US/champion.json"
        );
        const data = await res.json();
        setChampions(data.data);
      } catch (error) {
        console.log(error);
      }
    };
    getHeroes();
  }, []);

  return (
    <div>
      {Object.entries(champions).map(([championId, champion]) => (
        <p key={champion.key}>{championId}: {champion.name}</p>
      ))}
    </div>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:05:07