Next.js中Props传递查询字符串遇TypeError未定义错误求助
问题排查与解决
1. 先修复触发的运行时错误
报错的核心原因是部分餐厅数据对象没有name属性,或name值为undefined,导致调用toLowerCase()时抛出Cannot read properties of undefined错误。
修改RestaurantList组件的过滤逻辑,先做空值校验:
const searchQuery = data.restaurants.data.filter((restaurant) => { // 先确保name存在,再执行后续匹配逻辑 if (!restaurant.name) return false; // 同时统一转为小写,避免大小写不匹配 return restaurant.name.toLowerCase().includes(props.search?.toLowerCase() || ''); });
注:把参数名从
query改为restaurant,避免和外部变量混淆,提升代码可读性。
2. 解决props.search为空/undefined的问题
从pages/index.js的代码看,query状态初始值为空字符串,理论上不会传递undefined,但可以做以下兜底优化:
- 在
Home组件中给searchprop设置默认值:
<RestaurantList search={query || ''} />
- 在
RestaurantList组件中给props设置默认值,避免未传参的情况:
// 方式1:给props参数设置默认 function RestaurantList(props = { search: '' }) { // ...组件逻辑 } // 方式2:解构赋值时设置默认 function RestaurantList({ search = '' }) { // ...组件逻辑 }
3. 调试建议
- 在
RestaurantList组件开头添加日志,确认props传递情况:
function RestaurantList(props) { console.log('Received props:', props); // 打印整个props对象,检查search字段 // ...后续代码 }
- 检查GraphQL接口返回的
data.restaurants.data,确认所有餐厅对象都包含name字段,可能是接口返回数据不一致导致部分餐厅缺失该属性。
内容的提问来源于stack exchange,提问作者Shawn Walsh
相关产品推荐
相关产品推荐

