React组件传参后map报错及数据不显示问题求助
React 子组件接收状态数据为undefined的问题解决
问题现象
- 调用API将响应数据存入useState后,父组件通过
console.log()能正常看到数据,但传递给子组件进行map渲染时,出现错误:Cannot read properties of undefined (reading 'map') - 添加
{menFootwears && menFootwears.map(...)}判断后错误消失,但子组件MenShoes和WomenShoes中console.log显示数据为undefined,无法渲染内容,父组件数据打印正常
核心原因
- Props名称完全不匹配:父组件传递的props名称和子组件接收的参数名称不一致:
- 父组件传给子组件的是
data,但子组件试图接收menFootwears/womenFootwears - 父组件传递
onclick,子组件接收handleProductCard - 父组件传递
loadingStatus,子组件接收isLoading
- 父组件传给子组件的是
- Loading状态逻辑缺陷:两个异步请求独立修改
isLoading,后执行的请求会覆盖前一个的状态更新,可能导致加载状态提前结束,引发骨架屏与真实内容的切换异常
解决方案
1. 修正Props传递与接收的一致性
方式一:修改父组件传递的props名称
在Product.jsx中调整子组件调用时的props名称,匹配子组件的接收参数:
// Product.jsx 渲染部分 return ( <Box> <WomenShoes womenFootwears={womenFootwears} handleProductCard={handleProductCard} isLoading={isLoading}/> <MenShoes menFootwears={menFootwears} handleProductCard={handleProductCard} isLoading={isLoading}/> </Box> )
方式二:修改子组件的参数接收
在MenShoes/WomenShoes.jsx中调整参数解构,匹配父组件传递的props:
// MenShoes.jsx 组件定义 export default function MenShoes({data: menFootwears, onclick: handleProductCard, loadingStatus: isLoading}) { // 原有渲染逻辑保持不变 }
2. 修复Loading状态管理
使用Promise.all并行处理两个请求,确保所有请求完成后再关闭加载状态:
// Product.jsx 中的useEffect部分 React.useEffect(()=> { const fetchAllData = async () => { setIsLoading(true); try { // 并行发起两个请求 const [womenResponse, menResponse] = await Promise.all([ fetch('https://dummyjson.com/products/category/womens-shoes'), fetch('https://dummyjson.com/products/category/mens-shoes') ]); const womenData = await womenResponse.json(); const menData = await menResponse.json(); setWomenFootwears(womenData.products); setMenFootwears(menData.products); } catch (error) { console.error('数据加载失败:', error); } finally { // 无论成功失败都关闭加载状态 setIsLoading(false); } }; fetchAllData(); }, [])
3. 子组件添加安全渲染判断
在子组件的map前添加可选链操作符,避免因数据未加载完成导致的报错:
// MenShoes.jsx 中map部分 {menFootwears?.map((menFootwear)=> ( <Card key={menFootwear.id} {...其他属性}> // 卡片内容渲染 </Card> ))}
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

