React中更好的方法是更新对象数组中的属性

时间:2016-06-20 08:48:04

标签: javascript reactjs functional-programming

我正在为网站构建一个简单的购物车,并且一直致力于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})
},

2 个答案:

答案 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

答案 1 :(得分: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,
})