![](/img/trans.png)
[英]Is there a better way to add a property of an array of objects to another array than a for loop?
[英]A better way in React to update a property in an array of objects
我正在為網站構建一個簡單的購物車,並且一直在進行“ add to cart
操作。 在工作的同時,我覺得可能有一種更簡單,更優雅的方法。
這是開始狀態:
start_state = {
inventory: [
{sku: "product_1", price: 600, name: "Product 1"},
{sku: "product_2", price: 800, name: "Product 2"}
],
cart: []
}
這是所需的最終狀態:
start_state = {
inventory: [
{sku: "product_1", price: 600, name: "Product 1"},
{sku: "product_2", price: 800, name: "Product 2"}
],
cart: [
{sku: "product_1", quantity: 2},
{sku: "product_2", quantity: 1}
]
}
這是Im觸發的將其從初始狀態帶到新的final_state的函數, sku
參數是調用操作時傳入的狀態中的項:
addToCart: function (sku) {
let currentCart = this.state.cart
let itemInCart = _.findIndex(currentCart, ['sku', sku])
let newItem = { sku: sku }
if (itemInCart !== -1) {
let newQuantity = currentCart[itemInCart].quantity
newItem.quantity = newQuantity + 1
} else {
newItem.quantity = 1
}
let filteredCart = _.filter(currentCart, (item) => { return item.sku !== sku })
let newCart = _.concat(filteredCart, newItem)
this.setState({cart: newCart})
},
由於使用的是ES6,因此可以使用它的一些新功能(如findIndex
和Object.assign
來實現findIndex
功能。
addToCart: function(product) {
let index = this.state.cart.findIndex((x) => x.sku === product.sku);
if(index === -1) {
let newProduct = {sku: product.sku, quantity:1}
this.setState({cart : this.state.cart.concat([newProduct])})
}
else {
let newCart = Object.assign([], this.state.cart);
newCart[index].quantity = newCart[index].quantity+1;
this.setState({cart: newCart});
}
}
我認為這樣更好:
function getCardWithIncItem(currentCart, itemInCart) {
return [
...currentCart.slice(0, itemInCart),
Object.assign({}, currentCart[itemInCart], {
quantity: currentCart[itemInCart].quantity + 1,
}),
...currentCart.slice(itemInCart + 1),
];
}
function getCardWithNewItem(currentCart, sku) {
return [
...currentCart, {
sku: sku,
quantity: 1,
}
];
}
const currentCart = this.state.cart;
const itemInCart = _.findIndex(currentCart, ['sku', sku]);
const newCart = (itemInCart !== -1)
? getCardWithIncItem(currentCart, itemInCart)
: getCardWithIncItem(currentCart, sku);
this.setState({
cart: newCart,
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.