React遍历购物车披萨列表,选择尺寸触发onChange后如何更新对应价格
不需要额外创建复杂Map结构,用普通状态对象存储每个商品的选中价格即可解决问题,你目前的核心问题是没有给每个购物车商品单独维护选中尺寸对应的价格状态,所以一直固定显示price[0]。
修改步骤
- 新增状态存储每个商品的选中价格
// 状态key用商品唯一ID最优,暂时没有的话可以先用购物车遍历索引 const [selectedPriceMap, setSelectedPriceMap] = useState({});
- 修改handleChange方法,支持识别是哪个商品的选择发生变更
const handleChange = (productKey, e) => { const currentSelectedPrice = e.target.value; setSelectedPriceMap(prev => ({ ...prev, [productKey]: currentSelectedPrice })); };
- 修改渲染逻辑,补充PizzaSelect的value绑定,动态展示价格
{cart.products.map((product, index) => { // 优先用商品id做唯一标识,没有的话用index const productKey = product.id || index; // 取当前商品选中的价格,没有选中值时默认取第一个价格 const currentPrice = selectedPriceMap[productKey] ?? product.price[0]; return ( <Product key={productKey}> <ProductDetail> <Image src={product?.img} /> <Details> <ProductName> <b>Pizza:</b> {product?.name} </ProductName> {/* 补充value属性,绑定当前选中值,onChange传入当前商品标识 */} <PizzaSelect value={currentPrice} onChange={(e) => handleChange(productKey, e)} > {product.size.map((size, i) => ( <FilterSizeOption key={i} value={product.price[i]} >{size}</FilterSizeOption> ))} </PizzaSelect> </Details> </ProductDetail> <PriceDetail> <ProductPrice> €{currentPrice} </ProductPrice> <RemoveItemButton onClick={() => emptyCartByProduct(product)}>delete</RemoveItemButton> </PriceDetail> </Product> ) })}
补充说明
- 若你习惯使用ES6的Map结构也可以实现需求,只是React更新Map类型的状态时,需要创建新的Map实例才能触发重渲染,普通对象的写法更简洁。
- 尽量不要用遍历索引作为唯一key,有商品ID的话优先用ID,避免购物车商品顺序变动时出现状态错乱。
内容的提问来源于stack exchange,提问作者Ivan Petrovic
相关产品推荐
相关产品推荐

