React购物车选品报错:Cannot read properties of undefined (reading 'img')
问题根源分析
报错Uncaught TypeError: Cannot read properties of undefined (reading 'img')的核心原因:
- 选择属性后首次添加购物车时,
clr/sz因useState异步更新特性未同步到最新值,导致购物车项的color为undefined,在BasketItem中访问color.color触发报错。 - 多次点击属性后状态更新完成,此时添加的购物车项包含有效属性,渲染恢复正常。
- 额外问题:
BasketItem中直接渲染对象类型的color会显示[object Object],不符合预期。
具体解决方案
1. 给BasketItem添加属性安全访问
修改BasketItem组件,通过可选链和默认值避免属性为undefined时报错,同时优化颜色显示逻辑:
import s from "./BasketItem.module.scss"; const BasketItem = ({ img, name, price, size, color }) => { return ( <div className={s.basketitem}> <div className={s.imgandname}> <img src={img} alt={name} /> <div className={s.name}>{name}</div> </div> <div className={s.size}>{size || '未选择'}</div> <div style={{ backgroundColor: color?.color || 'transparent' }} className={s.color} > {color?.name || '未选择'} </div> <div className={s.value}>1</div> <div className={s.price}>{price}</div> </div> ); }; export default BasketItem;
2. 确保添加购物车时属性值有效
在ProductPage的添加按钮事件中,给size和color设置默认值,避免传入undefined:
<button onClick={(e) => buttonHandler({ id: id, img: img, name: name, size: sz || '未选择', color: clr || { color: 'transparent', name: '未选择' }, price: price, }) } className={s.btnopenshop} > Добавить в корзину </button>
3. 优化ProductPage初始状态匹配数据结构
将fetchedData初始值从数组[]改为对象{},接口返回的是单个商品对象,初始数组解构会导致所有属性为undefined,调整后更符合数据逻辑:
let [fetchedData, updateFetchedData] = useState({});
4. 解决useState异步更新延迟(可选)
如果父组件中sizef/colorf是通过useState更新clr/sz,可通过useRef保存最新值,确保添加购物车时获取的是实时属性:
// 父组件示例 import { useState, useRef, useEffect } from 'react'; const ParentComponent = () => { const [clr, setClr] = useState(null); const [sz, setSz] = useState(null); const clrRef = useRef(clr); const szRef = useRef(sz); // 同步ref与state useEffect(() => { clrRef.current = clr; szRef.current = sz; }, [clr, sz]); const buttonHandler = (item) => { const newCartItem = { ...item, color: clrRef.current || { color: 'transparent', name: '未选择' }, size: szRef.current || '未选择' }; // 执行添加到购物车的逻辑 }; // 渲染ProductPage时传入buttonHandler等参数 };
内容的提问来源于stack exchange,提问作者qweqwe
相关产品推荐
相关产品推荐

