You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Hook中useState()与setList异常:点击按钮触发map读取未定义错误

解决点击过滤按钮触发"Cannot read properties of undefined (reading 'map')"错误

问题情况

  • 页面初始渲染正常,所有餐厅都能通过map渲染到Restaurantcard组件
  • 点击按钮过滤avgRating>4的餐厅时,立刻抛出错误:TypeError: Cannot read properties of undefined (reading 'map')

错误根源

从代码逻辑来看,核心问题是点击按钮后更新的listofRestaurant变成了undefined,导致后续map调用失败。常见触发原因:

  • 过滤操作时,错误地将非数组值赋值给了state,比如不小心把单个对象或undefined传给了setListofRestaurant
  • 若过滤条件里的字段名写错(比如把avgRating写成avg_rating),一般只会返回空数组(空数组可正常map),所以更可能是state更新时的赋值错误

修复方案

1. 修正过滤逻辑的赋值

确保过滤后返回的是数组,再更新state:

const handleFilter = () => {
  const filtered = listofRestaurant.filter(res => res.avgRating > 4);
  setListofRestaurant(filtered);
};

同时检查mock数据里的字段名,确认每个餐厅对象确实有avgRating属性,避免过滤条件不生效。

2. 给state加数组兜底

不管初始化还是更新,都保证state是数组类型:

// 初始化时,即使mockData加载异常,也用空数组兜底
const [listofRestaurant, setListofRestaurant] = useState(mockData || []);

// 更新state时同样兜底
setListofRestaurant(filtered || []);

3. 渲染时加空值判断

在map前用可选链操作符判断数组是否存在,避免报错:

{listofRestaurant?.map(restaurant => (
  <Restaurantcard key={restaurant.id} data={restaurant} />
))}

这样即使listofRestaurant是undefined,map也不会执行,自然不会抛出错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:42:19