[英]setState of an object within an array
鑒於我的狀態如此:
cart: [
{ id: 1, name: 'apple', price: 100, quantity: 1 }
]
我如何setState
特定對象的quantity
財產?
您可以獲取indexOf
您要更新的cart
商品,並使用該商品,更新商品和其他商品更新cart
。
例
class App extends React.Component {
state = {
cart: [
{ id: 1, name: "apple", price: 100, quantity: 1 },
{ id: 2, name: "orange", price: 50, quantity: 10 },
{ id: 3, name: "banana", price: 20, quantity: 100 }
]
};
increaseQuantity = item => {
this.setState(previousState => {
const { cart } = previousState;
const itemIndex = cart.indexOf(item);
return {
cart: [
...cart.slice(0, itemIndex),
{ ...cart[itemIndex], quantity: cart[itemIndex].quantity + 1 },
...cart.slice(itemIndex + 1)
]
};
});
};
render() {
return (
<div>
{this.state.cart.map(item => (
<div key={item.id} onClick={() => this.increaseQuantity(item)}>
{item.name} {item.quantity}
</div>
))}
</div>
);
}
}
您可以將購物車更新為
updateCart(id, itemAttributes) {
var index = this.state.cart.findIndex(x=> x.id === id);
if (index === -1)
// handle error
else
this.setState({
cart: [
...this.state.cart.slice(0, index),
Object.assign({}, this.state.cart[index], itemAttributes),
...this.state.cart.slice(index+1)
]
});
}
然后使用您的購物車項目的ID調用您的updateCart函數
this.updateCart(1, {quantity: 2});
this.setState(prev => ({
cart: [{ ...prev.cart[0], quantity: 10, }].concat(prev.cart.slice(1))
}));
復制數組並使用復制的版本替換要更改的對象。 如果您經常這樣做,您可以使用一些實用程序:
const replace = index, replacer) => arr =>
arr.map((el, i) => i === index ? replacer(el) : el);
const key = (k, replacer) => state => ({...state, [k]: replacer(state[k]) });
適用於:
this.setState(key(
"cart",
replace(
0,
key("quantity", () => 10)
)
));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.