React函数组件传props后出现restaurants未定义及解构报错
问题排查与修复方案
核心错误定位
1. 子组件导出逻辑错误
查看RestaurantArray.js的最后一行代码:
export default RestaurantArray();
该写法是直接调用RestaurantArray函数并导出函数执行后的返回值,而非导出组件本身。
执行这段代码时,组件函数会在模块加载阶段被立即调用,此时没有任何外部传入的props,函数接收到的入参为undefined,完全匹配你遇到的两类报错:
- 解构写法下:尝试从undefined中解构
restaurants属性,触发TypeError: Cannot destructure property 'restaurants' of 'undefined' as it is undefined - 非解构写法下:尝试读取undefined的
restaurants属性,触发TypeError: Cannot read property 'restaurants' of undefined
2. 空值兜底逻辑缺失
即使修正了导出问题,如果后续存在props传递异常、接口返回空值的场景,直接对restaurants执行map操作仍会触发报错。
分步修复操作
- 修正子组件导出写法
去掉RestaurantArray后的调用括号,直接导出组件本身:// 错误写法 // export default RestaurantArray(); // 正确写法 export default RestaurantArray; - 为
restaurants属性增加空值兜底
修改RestaurantArray.js中的map调用,避免空值触发错误:
如果需要兼容不支持可选链的低版本环境,可将兜底逻辑替换为function RestaurantArray ( {restaurants} ) { return( <div className = "RestaurantArray"> { // 可选链兜底,restaurants为null/undefined时直接短路,不执行map restaurants?.map(restaurant => { return <Restaurant restaurant={restaurant} key={restaurant.id} />; }) } </div> ); }(restaurants || []).map(...) - 清理App.js中的潜在隐患
- 移除未使用的
useEffect导入,减少冗余代码 - 补充
<SearchBar />组件的导入逻辑,否则运行时会触发组件未定义报错
修正后的App.js参考代码:
import React, {useState} from 'react'; import RestaurantArray from './components/RestaurantArray.js'; // 按需补充SearchBar导入 // import SearchBar from './components/SearchBar.js'; function App() { const [restaurants, setRestaurants] = useState([]); return ( <div className="App"> <header className="App-header"> <SearchBar /> <RestaurantArray restaurants={restaurants}/> </header> </div> ); } export default App; - 移除未使用的
注意:App.js中传递props的语法
restaurants = {restaurants}本身是正确的,无需调整。
内容的提问来源于stack exchange,提问作者heyblah
相关产品推荐
相关产品推荐

