0
我正在爲一個站點構建一個簡單的購物車,並一直致力於add to cart
操作。雖然我有工作,但我覺得可能有一個簡單更優雅的方法。React更好地更新對象數組中的屬性
這是起始狀態:
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}
]
}
而這是函數林觸發把它從初始狀態到新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? – QoP
是的,使用巴貝爾來傳遞 –