我在共享相同狀態的陣列中有一些元素。我只需要更新被點擊的那一項,就可以向我的購物車中再添加一件商品。我怎樣才能在不改變其他人的情況下做到這一點?
我的初始狀態如下所示:
class ShoppingCart extends Component {
constructor() {
super();
this.state = {
isEmpty: true,
cartItems: [],
count: 0,
};
this.getStoredProducts = this.getStoredProducts.bind(this);
this.handleButtonIncrease = this.handleButtonIncrease.bind(this);
}
componentDidMount() {
this.getStoredProducts();
}
handleButtonIncrease() {
this.setState((prevState) => ({
count: prevState.count 1,
}));
}
getStoredProducts() {
const getFromStorage = JSON.parse(localStorage.getItem('cartItem'));
if (getFromStorage !== null) {
this.setState({
cartItems: getFromStorage,
}, () => {
const { cartItems } = this.state;
if (cartItems.length) {
this.setState({ isEmpty: false });
}
});
}
}
render() {
const { isEmpty, cartItems, count } = this.state;
const emptyMsg = (
<p data-testid="shopping-cart-empty-message">Seu carrinho está vazio</p>
);
return (
<div>
{ isEmpty ? (emptyMsg) : (cartItems.map((item) => (
<ShoppingCartProduct
key={ item.id }
id={ item.id }
count={ count }
cartItems={ item }
handleButtonIncrease={ this.handleButtonIncrease }
/>
)))}
</div>
);
}
}
uj5u.com熱心網友回復:
看來這應該是ShoppingCartProduct的責任。如果您從組件中洗掉此count和setCount邏輯并在ShoppingCart組件內部創建它ShoppingCartProducts,則每個專案都有自己的count狀態,可以獨立更新。
另一種查看方式是直接改變 each cartItem,但由于您沒有指定它們的格式,因此無法知道它們是否存盤了有關數量的任何資訊,因此我將采用第一種方法。
uj5u.com熱心網友回復:
handleButtonIncrease可以接受item.id作為引數,以便它可以更新state.cartItems.
handleButtonIncrease(itemId) {
const cartItems = this.state.cartItems.map(item => {
return item.id === itemId
? {
// apply changes here for the item with itemId
}
: item
});
this.setState((prevState) => ({
cartItems,
count: prevState.count 1,
}));
}
之后,也更新您的回呼:
handleButtonIncrease={ () => this.handleButtonIncrease(item.id) }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/364574.html
標籤:反应
下一篇:無法使用地圖渲染axios的回應
