React的扩展运算符从useState中传播后,在正确使用函数一次后变为undefined?

huangapple go评论69阅读模式
英文:

React spread operator from useState undefined after correctly using function once?

问题

I have an object array that looks like this

index:
    product: data: id: 
    quantity:

I have a shop that when items are added they need to be added to the cart. If the user adds the same object to the cart multiple times I just need the quantity of that item to update.

For some reason when adding the same item to the cart the quantity gets updated correctly the first time. The second time I add the same item to the cart my temp variable that copies the useState array becomes undefined and my quantity value becomes NaN. Using .slice() yielded the same results.

basically:
I add the first item to the cart. I add the same item to the cart with another quantity it updates fine. If add it again the temp var is undefined and my value is now NaN.

   const [cart, setCart] = React.useState([])

const addToCart = (data) => {
    const index = cart.findIndex(ele => ele.product.data.id === data.product.data.id)
    if (index !== -1) {
        let temp = [...cart]
        temp[index] = { ...temp[index], quantity: (data.quantity.value + temp[index].quantity.value) }
        setCart([...temp])
    }
    else {
        setCart([...cart, data])
    }
}
英文:

I have an object array that looks like this

index:
    product: data: id: 
    quantity:

I have a shop that when items are added they need to be added to the cart. If the user adds the same object to the cart multiple times I just need the quantity of that item to update.

For some reason when adding the same item to the cart the quantity gets updated correctly the first time. The second time I add the same item to the cart my temp variable that copies the useState array becomes undefined and my quantity value becomes NaN. Using .slice() yielded the same results.

basically:
I add the first item to the cart. I add the same item to the cart with another quantity it updates fine. If add it again the temp var is undefined and my value is now NaN.

   const [cart, setCart] = React.useState([])

const addToCart = (data) => {
    const index = cart.findIndex(ele => ele.product.data.id === data.product.data.id)
    if (index !== -1) {
        let temp = [...cart]
        temp[index] = { ...temp[index], quantity: (data.quantity.value + temp[index].quantity.value) }
        setCart([...temp])
    }
    else {
        setCart([...cart, data])
    }
}

答案1

得分: 1

我认为这是其中一个最常见的问题。请阅读这份文档

我认为这可能会有所帮助:

   const [cart, setCart] = React.useState([])

   const addToCart = (data) => {
     const nextCart = cart.map((cartItem, cartIndex) => {
      if (cartItem.product.data.id === data.product.data.id) {
       // 返回具有更新值的新购物车项目
       return {
        ...cartItem,
        quantity: cartItem.quantity.value + data.quantity.value
       };
      
       } else {
       // 无变化
       return cartItem;
      }
     });

     setCart(nextCart);
   }

另外,如果你想直接更新对象或数组状态,你也可以使用immer

英文:

I think it is one of the most common problems. Please read this documentation.

I think it may help:

   const [cart, setCart] = React.useState([])

   const addToCart = (data) => {
     const nextCart = cart.map((cartItem, cartIndex) => {
      if (cartItem.product.data.id === data.product.data.id) {
       // Return a new cart item with updated values
       return {
        ...cartItem,
        quantity: cartItem.quantity.value + data.quantity.value
       };
      
       } else {
       // No change
       return cartItem;
      }
     });

     setCart(nextCart);
   }

Also you can use immer if you want update your object or array state directly.

答案2

得分: 1

你的数据结构在调用 addToCart 时不一致。

看起来你的基本状态是一个对象数组,至少具有以下结构:

const cartItem = {
  product: {
    data: { id: 1 },
    quantity: { value: 1 },
  },
};

但当你调用 addToCart 时,这行代码改变了你的购物车项的结构:

temp[index] = { ...temp[index], quantity: (data.quantity.value + temp[index].quantity.value) }

我们可以重新格式化一下,使其更易读:

temp[index] = {
  ...temp[index], // 复制现有对象
  quantity: (data.quantity.value + temp[index].quantity.value), // 覆写数量
  // 但现在数量是一个数字,不是一个对象
};

因此,当你再次调用 addToCart 时,状态中的值现在看起来像这样:

const cartItem = {
  product: {
    data: { id: 1 },
    quantity: 2,
  },
};

与上面的 cartItem 进行比较,你会看到 quantity 的结构现在不同了。

那个有问题的行应该改成这样:

temp[index] = {
  ...temp[index],
  quantity: {
    ...temp[index].quantity,
    value: data.quantity.value + temp[index].quantity.value,
  },
};

尝试一下,看看是否有帮助!

英文:

Your data structure is inconsistent between your calls to addToCart.

It looks like your base state is an Array of objects with at least the following structure:

const cartItem = {
  product: {
    data: { id: 1 },
    quantity: { value: 1 },
  },
};

But when you call addToCart, this line of code is changing the structure of your cart item:

temp[index] = { ...temp[index], quantity: (data.quantity.value + temp[index].quantity.value) }

We could re-format that so it's a little easier to read:

temp[index] = {
  ...temp[index], // Copy the existing object
  quantity: (data.quantity.value + temp[index].quantity.value), // Over-write quantity
  // But now quantity is a number, not an object
};

So when you call addToCart again, the value from your state now looks like this:

const cartItem = {
  product: {
    data: { id: 1 },
    quantity: 2,
  },
};

Compare that to cartItem above; you'll see that the structure for quantity is now different.

What that problematic line should read is this:

temp[index] = {
  ...temp[index],
  quantity: {
    ...temp[index].quantity,
    value: data.quantity.value + temp[index].quantity.value,
  },
};

Try that and see if it helps!

huangapple
  • 本文由 发表于 2023年4月20日 03:24:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76058156.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定