【问题标题】:how to add new property to react useContext state如何添加新属性以响应 useContext 状态
【发布时间】:2021-09-05 19:54:13
【问题描述】:

我有一个小问题,我正在学习reactjs。我正在尝试向购物车数组中名为数量的对象添加一个属性;当具有相同 id 的相似项等于迭代器时,添加一个属性数量并增加它的值。我正在学习 react 和 javascript 我来自 python 背景所以...... 这是我的代码。

 const addToCart = (item) => {
    if (cart.length){
        for (let iter of cart){
            if (iter.id===item.id){
                item.quantity += 1 // this is 'NaN' if quantity wasn't declared.
                setCart([...cart, item])
            }else{
                setCart([...cart, item])
            }
        }
    }
}

这段代码……什么都没有!

【问题讨论】:

  • 即使找到了 id,您的代码似乎也会将 item 添加到数组中。这是故意的吗?
  • 不,我还在学习 react 和 js,我想做的是在项目对象中创建一个名为数量的属性,如果迭代器 ID 和项目 ID 匹配,则更新其值。跨度>
  • 当我在更新数量值后手动将商品推送到购物车时。它也什么都不做。

标签: reactjs state react-state-management use-context


【解决方案1】:

如果我对您的理解正确,如果商品存在于购物车中,您想增加数量,否则将其添加到购物车中?如果是这样,请尝试以下操作:

const [cart, setCart] = useState([]);

...

const addToCart = (item) => {
    // declare the quantity property if it doesn't exist
    item.quantity = item.quantity || 1;
    // get the index from the cart
    const i = cart.findIndex(obj => obj.id === item.id);
    // if the item exists increment the quantity
    if(i > -1) {
      const newCart = [...cart];
      newCart[i].quantity = item.quantity + 1; 
      setCart(newCart)
    } else {
      // the item doesn't exist so add it to the cart
      setCart([...cart, item]);
    }
 }

【讨论】:

  • 是的,这就是我想要做的。
  • 是的,我做到了,它不会抛出错误,但也不起作用。
  • 就像我说的,我真的不知道 react 和 js 的工作原理,但是在将 if(cart.length){} 更改为 if(cart){} 之后,它开始工作了。
  • 如果没有最小的可重现示例,很难找到问题,但我认为如果您确定 cart 始终是一个数组,您可以摆脱这个测试
  • 是的,它总是一个对象数组。
猜你喜欢
  • 2022-08-16
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
  • 2017-05-27
  • 2011-03-30
  • 1970-01-01
  • 2019-11-09
  • 2021-03-16
相关资源
最近更新 更多