Redux功能一键后退

时间:2017-12-14 09:59:09

标签: javascript reactjs redux

我有这个:

case "ADD_TO_BASKET":
      return { items: addProductToBasket(state.items, action), total: calculateTotal(state.items)}

const calculateTotal = (items) => {
  return items.reduce((totalPrice, basketItem) => {
    const price = basketItem.product.price;
    const quantity = basketItem.quantity;
    const total = price * quantity;
    console.log('here calc2');
    return totalPrice + total
  }, 0)
}

const addProductToBasket = (items, action) => {
  if (isProductInBasket(items, action)) {
    return items.map((product) => {
      if (product.product.id == action.data.product.id) {
         return {...product, quantity: product.quantity + 1}
      }
      return product;
    });
  }
  else {
    const basketState = [].concat(items).concat({...action.data, quantity: 1})
    return basketState;
  }
}

问题是,当我调用此函数时,每次正确单击时它都会更新项目,但总是一次点击后面。例如,如果我调用它一次然后总数为0,它应该是20并且如果我再次点击它总数应该是40但实际上只有20.可以发布更多代码但是任何理由为什么它会落后一步可以这么说?

1 个答案:

答案 0 :(得分:0)

您应该删除已添加的附加参数以减少功能。在初始迭代期间,第一个参数将值取为0.尝试使用此

const calculateTotal = (items) => {
  let totalPrice = 0
  return items.reduce((basketItem) => {
    const price = basketItem.product.price;
    const quantity = basketItem.quantity;
    const total = price * quantity;
    console.log('here calc2');
    return totalPrice + total
  })
}