2016-06-20 63 views
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}) 
}, 
+0

您使用ES6? – QoP

+0

是的,使用巴貝爾來傳遞 –

回答

1

由於您使用ES6,你可以使用它的一些新功能,如findIndexObject.assign達到你想要的東西。

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}); 
     } 
} 

full working example

0

我覺得這種方式較好:

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, 
})