如何将商品数据存入useState对象并实现数组式存储?
解决方案
1. 修正上下文状态的初始值
首先在_app.js中,把card的初始状态从单个对象改为空数组,同时修正拼写错误(scroe → score):
export default function MyApp({ Component, pageProps }) { const [count, setcount] = useState(0); // 初始化为空数组,用于存储多个商品对象 const [card, setcard] = useState([]); return ( <AppContext.Provider value={{ count, setcount, card, setcard, }} > <Layout> <Component {...pageProps} /> </Layout> </AppContext.Provider> ); }
2. 正确获取商品数据并添加到购物车
你之前的错误是试图从e.target获取item,但e.target是按钮DOM元素,并不包含item对象。直接使用map循环中的item即可(闭包会保留当前迭代的item)。
同时,要避免每次点击覆盖原有数据,需要用函数式更新将新商品对象追加到数组中:
<Button sx={{ width: 308 }} variant="contained" endIcon={<AddShoppingCartIcon />} onClick={() => { // 用函数式更新count,避免状态依赖问题 context.setcount(prevCount => prevCount + 1); // 构建当前商品的完整对象 const newCartItem = { pic: item.itemMainPic, des: item.itemName, price: item.rangePriceFormat, score: item.score }; // 将新商品追加到购物车数组 context.setcard(prevCard => [...prevCard, newCartItem]); }} > add to card </Button>
3. 验证结果
此时多次点击按钮后,执行console.log(context.card)会得到你期望的数组结构:
[ { "pic": "https://valid URL1.jpg","des": "something", "score": "something", "price": "something"}, { "pic": "https://valid URL2.jpg","des": "something", "score": "something", "price": "something"}, { "pic": "https://valid URL3.jpg","des": "something", "score": "something", "price": "something"} ]
内容的提问来源于stack exchange,提问作者daan
相关产品推荐
相关产品推荐

