You need to enable JavaScript to run this app. React+Axios+Redux场景下API数据已存在但组件无法渲染问题求助
优惠活动
大模型
产品
解决方案
定价
更多

React+Axios+Redux场景下API数据已存在但组件无法渲染问题求助

问题原因

  1. heroesInfo.map的回调函数使用了大括号包裹逻辑,但没有显式返回<Heroes />组件,导致遍历后没有生成任何可渲染的节点,页面自然空白。
  2. useEffect的依赖项错误填写了Home组件本身,会导致请求逻辑重复触发,实际仅需在组件首次挂载时拉取数据,依赖项填空数组即可。
  3. 列表渲染未添加唯一key属性,后续运行会出现React警告,建议添加对应唯一标识。

修正后的代码

Home组件调整

const Home = () => {
    const dispatch = useDispatch();
    // 依赖项改为空数组,仅首次挂载执行请求
    useEffect(() => {
      dispatch(fetchHeroes());
    }, []);
    const { heroesInfo } = useSelector((state) => state.HeroesInfoAll);
    return (
      <div>
        <HeroList>
          {/* 使用圆括号隐式返回组件,同时添加key属性、传递单个英雄数据 */}
          {heroesInfo.map((heroItem, index) => (
            <Heroes heroInfo={heroItem} key={index} />
          ))}
        </HeroList>
      </div>
    );
};

Heroes组件调整(可选,用于展示对应英雄数据)

// 接收父组件传递的单个英雄数据
const Heroes = ({ heroInfo }) => {
  return (
    <>
      <h1>{heroInfo.heroName}</h1>
      <div className="hero-image">
        <img src={heroInfo.heroImg} alt={heroInfo.heroName} />
      </div>
      <h2>{heroInfo.heroType}</h2>
      <h2>{heroInfo.attackType}</h2>
    </>
  );
};
export default Heroes;

注:上述Heroes组件中的字段名需要替换为你实际接口返回的对应字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 05:39:04