React.js计算各对象数组总价并渲染到表格单元格方法
实现方案
你只需要在遍历每一组商品时,累加组内所有商品的totalPrice得到分组合计值,直接填入对应空的<td>单元格即可,计算结果和你预期的405、198、336完全一致。
核心计算逻辑
对每个内层商品分组数组,用reduce方法做累加即可:
// items为当前遍历到的内层商品数组 const groupTotal = items.reduce((sum, item) => sum + item.totalPrice, 0)
修改后的完整表格代码
代码里补了React列表渲染要求的key属性,避免控制台抛出渲染警告:
<table className='table'> <thead> <tr> <th scope='col'>Items</th> <th scope='col'>Total Items Price</th> </tr> </thead> <tbody> {cardItems.map((items, groupIndex) => ( <tr key={groupIndex}> <td> {items.map((item, itemIndex) => ( <React.Fragment key={itemIndex}> <b className='mc-red'>{item.title}</b> Item Price:{' '} {item.price} LE, Item Count: {item.count}, Item Total Price:{' '} {item.totalPrice} LE <br /> </React.Fragment> ))} </td> <td> {items.reduce((sum, item) => sum + item.totalPrice, 0)} LE </td> </tr> ))} </tbody> </table>
渲染效果
表格三行的总价列会按顺序展示:
- 第一组(McRoyale、Big Mac):405 LE
- 第二组(Double Big Tasty):198 LE
- 第三组(Grand Chicken Premier、Spicy Chicken Fillet):336 LE
完全匹配预期要求。
内容的提问来源于stack exchange,提问作者yasser Eltibili
相关产品推荐
相关产品推荐

