简体   繁体   English

Redux功能一键落后

[英]Redux function one click behind

I have this: 我有这个:

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

the problem is that when I call this function it updates items everytime i click correctly but total is always one click behind. 问题是,当我调用此函数时,每次我单击正确时它都会更新项目,但总数始终落后一击。 for example if i call it once then total is 0 when it should be 20 and if i click it again the total should be 40 but is actually only 20. can post more code but any reason why it would be one step behind so to speak? 例如,如果我调用一次,则总数应为0,应为20;如果再次单击,总数应为40,但实际上仅为20。可以发布更多代码,但可以说这是落后一步的任何原因?

You should remove the additional param you have added to reduce function. 您应该删除为减少功能而添加的其他参数。 During initial iteration the first parameter takes the value as 0. Try with this 在初始迭代期间,第一个参数将值设为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
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM