reactjs - 为什么映射项状态在 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>
解决方案
您应该始终在数组内的项目上使用 key 道具。例如,如果您有一个 id,则如下所示:
<div className="product-in-cart" key={productInCart.id}>...</div>
React 使用 key 来正确识别数组中的项目。您的问题可能有所不同,但您应该始终使用密钥
编辑:productQuantity
应该是productInCart.productQuantity
;)
推荐阅读
- android - 如果图像是 HTTP 格式,Imageview 将不会显示带有 piccsso 的图像
- javascript - 自动对焦表单中活动 div 内的第一个表单元素
- r - 在 paste 和 paste0 中连接特殊字符串
- c++ - 如何读取一串布尔运算并赋予其优先级?
- php - 有没有办法在 Symfony 中拥有实体属性,它包含同一实体的属性组合?
- node.js - PermissionError: [Errno 13] Permission denied - 通过运行 python 脚本
- node.js - 有没有办法实现上传文件并从 MERN 中的服务器查看它们的方法?
- reactjs - 使用 withRouter 的 React-Router + React Hooks
- python - 为什么我的代码没有超过前 2 行
- python - Python ping 脚本在第一次尝试时总是失败