【问题标题】:add object to an existing array of objects React Recoil将对象添加到现有的对象数组 React Recoil
【发布时间】:2021-08-03 09:25:56
【问题描述】:

当反应反冲中的 id 不匹配时,我想向对象数组添加一个新对象

const [cart, setCart] = useRecoilState(cartItems)

对象 {id:1, quantity:1, productName:'apple'}

const addToCart =(object) => {
        
        if(cart.length==0){
            setCart([object])
        }
        else{
            let data = cart.map(items=>
                {
                    if(items.id == object.id )
                    {
                        return {...items, quantity:items.quantity + cartData.quantity}
                    }else
                    {
                        
                    }
                })                
            setCart(data)
        }
}

【问题讨论】:

  • 您的问题或问题是什么?
  • 它是一个购物车要添加一个新项目,如果项目已经存在,只需增加它的数量

标签: reactjs recoiljs


【解决方案1】:

你可以使用

findIndex()

找到满足您条件的元素。如果找不到任何东西,它会返回 -1。

const index = cart.findIndex(item => item.index == object.id);
if (index == -1) setCart([...cart, object])
else ...

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2018-09-06
    相关资源
    最近更新 更多