我不确定问题的标题是否正确。我遇到了一些问题,我不知道如何解决。
在我的应用程序中,有购物车页面,有物品列表。每个项目都有一个字段数量,可以更新。我的问题是当我启动状态数量并从中增加和减少数量的两个功能时出现问题。但是问题是当我单击addQuantity时,它会同时更新所有产品数量。我最近几天一直想找出解决这个问题的办法。这是两个项目。
这些是我的密码
CartContainer类扩展了React.Component {状态= {数量:1,};
componentDidMount(){this.props.getItemwegoToCart(); }
render(){
const addItem = () => {
this.setState({
quantity: this.state.quantity + 1,
});
};
const removeItem = () => {
this.setState({
quantity: this.state.quantity - 1,
});
};
Cart.js
return cartData.map((item,index)=> {return(
<Grid item xs={4} container justify="space-around">
<CartItemDetails
quantity={quantity}
addItem={addItem}
removeItem={removeItem}
addQty={addQuantity}
subQty={subtractQuantity}
cart={item}
/>
</Grid>
</Grid>
</Grid>
);
CartItemDetail.js
return (
<Grid container className="cart-item-details">
<Grid xs={12} md={4}>
{!this.props.team ? (
<Grid className="counter" xs={12} container>
<Grid container justify="center" alignItems="center" xs={4}>
<button
onClick={this.props.removeItem}
className="decrement"
></button>
</Grid>
<Grid container justify="center" alignItems="center" xs={4}>
<span>{this.props.quantity}</span>
</Grid>
<Grid container justify="center" alignItems="center" xs={4}>
<button
onClick={this.props.addItem}
className="increment"
></button>
</Grid>
</Grid>
) : (
""
)}
任何帮助都会很大,我真的很想解决这个问题。
像下面这样声明你的状态
state={
quantity:{}
}
使用产品ID或独特的东西作为数量的关键
const addItem = (id) => {
this.setState({
quantity: {
...this.state.quantity,
[id]:this.state.quantity[id]+1
}
});
};
const removeItem = (id) => {
this.setState({
quantity: {
...this.state.quantity,
[id]:this.state.quantity[id]-1
}
});
};
<Grid item xs={4} container justify="space-around">
<CartItemDetails
quantity={this.state.quantity[id]||0}
addItem={addItem}
removeItem={removeItem}
addQty={addQuantity}
subQty={subtractQuantity}
cart={item}
/>
</Grid>
</Grid>
</Grid>
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句