React中map函数内实现乘法计算购物车总价的技术咨询
React购物车总价计算实现方案
前置注意事项
- 首先要做异常兼容,避免localStorage无cart数据、cart数组和localStorage存储的商品数量数组长度不匹配导致的索引报错
- 价格计算要注意精度问题,避免浮点数运算出现多位数小数的情况
实现逻辑
你可以在渲染购物车列表的逻辑之外,通过Array.reduce方法累加计算总价,核心逻辑是:
- 先安全读取localStorage中的购物车数量数据,不存在的话默认是空数组
- 遍历API返回的商品列表,匹配对应localStorage中的商品数量,相乘后累加
- 最终结果保留2位小数展示即可
完整修改后代码
// 安全读取localStorage,防止无数据时报错 const storage = JSON.parse(localStorage.getItem("cart")) || []; // 计算总价 const totalPrice = cart.reduce((sum, order_item, index) => { // 兼容索引不存在的情况,数量默认取0 const quantity = storage[index]?.Quantity || 0; // 先转整数运算避免浮点数精度问题 return sum + (quantity * 100) * (Number(order_item.Price) * 100) / 10000; }, 0).toFixed(2); // 渲染购物车列表 cart.map((order_item, index) => { // 兼容拿不到数量的情况 const quantity = storage[index]?.Quantity || 0; return ( <li key={index} className="header-cart-item flex-w flex-t m-b-12" > <div className="header-cart-item-img"> <img src={order_item.image} alt="IMG" /> </div> <div className="header-cart-item-txt p-t-8"> <a href="#" className="header-cart-item-name m-b-18 hov-cl1 trans-04" > {order_item.title} </a> <span className="header-cart-item-info"> {quantity} x {order_item.Price}$ </span> </div> </li> ); }) // 需要展示总价的位置直接使用 {totalPrice}$ 即可
额外优化建议
- 不要用index作为map的key,建议改用商品的唯一ID,避免数组顺序变化时出现渲染异常
- 可以在localStorage存储购物车数据时也保存商品ID,匹配的时候用ID匹配而不是索引匹配,避免API返回的商品顺序变化时数量对应错误的问题
内容的提问来源于stack exchange,提问作者adel bouakaz
相关产品推荐
相关产品推荐

