You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React开发中如何在JSX map渲染前对购物车数组去重

实现方案

你要在map执行前完成数组去重,按照购物车的业务场景,一般以商品的唯一id作为去重依据(如果你的商品没有id字段,也可以替换为name等其他唯一标识字段),提供两种常用实现方式:

方式1:基于Map快速去重(代码最简)

利用Map键的唯一性实现去重,直接在getCart函数的map操作前插入去重逻辑即可:

function getCart(products) {
    // 按商品id去重,没有id就把p.id换成p.name
    const uniqueProducts = Array.from(new Map(products.map(p => [p.id, p])).values())
    return uniqueProducts.map((product) =>
        // 注意:key不要用index,用商品唯一id避免渲染异常
        <div key={product.id} style={{ borderBottom: "1px solid #d5cfcf" }} >
            <img src={product.image} style={{ width: '100%' }} alt="" />
            <div className="cart-info">
                <div>
                    <img src={close} onClick={() => 
                        cartReducer({ product, type: 'remove' })} style={{ width: 30, paddingLeft: 10 }} alt="" />
                </div>
                <div>
                    {product.name}
                </div>
            </div>
        </div>
    )
}

方式2:基于reduce去重(符合你提到的提前用reduce处理的需求)

如果需要在去重同时做其他数据处理,可以用reduce实现:

function getCart(products) {
    const uniqueProducts = products.reduce((acc, current) => {
        // 判断当前商品是否已经在累计数组中
        const isExist = acc.find(item => item.id === current.id)
        if(!isExist) {
            acc.push(current)
        }
        return acc
    }, [])
    return uniqueProducts.map((product) =>
        <div key={product.id} style={{ borderBottom: "1px solid #d5cfcf" }} >
            <img src={product.image} style={{ width: '100%' }} alt="" />
            <div className="cart-info">
                <div>
                    <img src={close} onClick={() => 
                        cartReducer({ product, type: 'remove' })} style={{ width: 30, paddingLeft: 10 }} alt="" />
                </div>
                <div>
                    {product.name}
                </div>
            </div>
        </div>
    )
}

额外优化建议

如果你的购物车需要统计同款商品的购买数量,建议去重逻辑直接放在cartReducer里处理,添加商品时就判断是否已存在,避免重复数据进入cart数组,性能比渲染前去重更好。

内容的提问来源于stack exchange,提问作者user12450400

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:18:00