首页 > 解决方案 > 为什么映射项状态在 React 中会相互影响?

问题描述

我映射了一个产品数组,每个产品都有,我用redux管理状态,如果我增加数量,每个映射的项目都有数量,价格也应该增加,所以当我改变一个项目的数量时,第二个数组价格也会根据以前的物品数量,那么为什么不同的物品会相互影响呢?这是代码:

const handleProductQuantity = (event) => {
    dispatch(setProductQuantity(event.target.value));
}

 <div className='cart'>
        <div className='products-in-cart-wrapper'>
        { productsInCart ? (
             productsInCart.map(productInCart => (
                    <div className='product-in-cart'>
                        <div className="product-in-cart-name">
                            <div className="label label-title">
                              Title:
                            </div>
                            <div className="value value-title">
                                {productInCart.title}
                             </div>
                        </div>

                        <div className="product-in-cart-price">
                             <div className="label label-price">
                                Price:
                             </div>
                             <div className="value value-price">
                                {productQuantity * productInCart.price}
                             </div>
                        </div>

                        <div className="product-in-cart-price">
                             <div className="label label-price">
                                Quantity:
                             </div>
                             <div className="value value-quantity">
                                <input onChange={handleProductQuantity} type="number" placeholder='1'/>
                             </div>
                        </div>
                        <div className="button-cont">
                            <button className="buy-button" onClick={test}>
                                Buy now
                            </button>
                        </div>
                    </div>
            ))
        ) : (
            <div> Loading... </div>
        )
        }
        <div className="total-price-button-cont">
            <button>Buy all for: 100$</button>
        </div>
        </div>
    </div>

标签: reactjs

解决方案


您应该始终在数组内的项目上使用 key 道具。例如,如果您有一个 id,则如下所示:

<div className="product-in-cart" key={productInCart.id}>...</div>

React 使用 key 来正确识别数组中的项目。您的问题可能有所不同,但您应该始终使用密钥

编辑:productQuantity应该是productInCart.productQuantity;)


推荐阅读