React+Axios+Redux场景下API数据已存在但组件无法渲染问题求助
问题原因
heroesInfo.map的回调函数使用了大括号包裹逻辑,但没有显式返回<Heroes />组件,导致遍历后没有生成任何可渲染的节点,页面自然空白。useEffect的依赖项错误填写了Home组件本身,会导致请求逻辑重复触发,实际仅需在组件首次挂载时拉取数据,依赖项填空数组即可。- 列表渲染未添加唯一
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
相关产品推荐
相关产品推荐

