fetch获取数据后调用items.map报TypeError错误,该如何解决?
解决「Uncaught (in promise) TypeError: items.map is not a function」错误
1. 修正初始state类型
map仅能作用于数组,所以组件初始state中存储数据的字段必须设为空数组,而非null、undefined或对象:
// 正确写法 const [items, setItems] = useState([]); // 错误写法(首次渲染会触发map报错) const [items, setItems] = useState(null);
2. 校验接口返回的数据结构
服务器返回的数据可能并非直接数组,而是嵌套在对象中(比如{ data: [...] }),先打印返回值确认结构:
fetch('/api/hotels') .then(res => res.json()) .then(data => { console.log(data); // 查看实际返回的数据格式 // 若数据嵌套在data.data字段,就取该数组;否则直接使用data setItems(data.data || data); }) .catch(err => console.error(err));
同时检查Mongoose查询代码,确保返回的是数组:
// 服务器端正确返回数组示例 Hotel.find({}) .then(hotels => res.json(hotels)) // 直接返回查询到的数组 .catch(err => res.status(500).json({ error: err.message }));
3. 处理请求异常与非JSON响应
若请求失败或返回非法JSON,res.json()会报错,可能导致state未被正确设置。添加错误处理逻辑:
fetch('/api/hotels') .then(res => { if (!res.ok) throw new Error('请求失败'); return res.json(); }) .then(data => { // 确保数据是数组再更新state setItems(Array.isArray(data) ? data : []); }) .catch(err => { console.error(err); setItems([]); // 出错时设为空数组,避免渲染报错 });
4. 渲染前做数组校验
在调用map前,先判断items是否为数组,或使用可选链操作符规避空值:
// 写法1:条件渲染 {Array.isArray(items) && items.map(item => ( <div key={item._id}>{item.name}</div> ))} // 写法2:可选链+空值合并 {items?.map(item => ( <div key={item._id}>{item.name}</div> )) || []}
内容的提问来源于stack exchange,提问作者Jayden
相关产品推荐
相关产品推荐

