简体   繁体   English

useState 删除 state 中包含 object 的数组元素

[英]useState delete array element in the state containing object

my state orderDetail contain orderDetail json我的 state orderDetail 包含 orderDetail json

I am getting the _id of the order which I want to delete in function eg _id: 60f1ab20891ced4818b5ea87,我得到了要在 function 中删除的订单的 _id,例如 _id: 60f1ab20891ced4818b5ea87,

now I want to remove this order from the orders array which is in orderdetail and update the state.现在我想从 orderdetail 中的 orders 数组中删除这个订单并更新 state。

orderdetail = {
  _id: 60f1ab20891ced4818b5ea86,
  totalPrice: '400',
  orders: [
    {
      _id: 60f1ab20891ced4818b5ea87,
      quantity: '1',
      price: 200,
      name: 'Caramel Latte',
      category: 'Steaming Cups'
    },
    {
      _id: 60f1ab20891ced4818b5ea88,
      quantity: '1',
      price: 200,
      name: 'Cinnamon Latte',
      category: 'Steaming Cups'
    }
  ],
  confirm: 'done',
  timestamp: 1626450720332,
  name: 'xxx',
  email: 'xxx',
}

what I did is clone state then uses for loop to find an index of the order then remove that index element in clone then update state to clone.我所做的是克隆 state 然后使用 for 循环查找订单的索引,然后在克隆中删除该索引元素,然后更新 state 以进行克隆。 any other less computation method?还有其他更少的计算方法吗?

What you need to so is set a new object with the orders array filtered as well as a new totalPrice .您需要做的是设置一个新的 object ,其中过滤orders数组以及一个新的totalPrice

For example例如

const [orderDetail, setOrderDetail] = useState( /* whatever */ )

const deleteOrder = (id) => {
  setOrderDetail(prev => {
    // filter out the order by ID
    const orders = prev.orders.filter(({ _id }) => _id !== id)
   
    return {
      ...prev,
      orders, // overwrite orders
      totalPrice: orders.reduce((total, { quantity, price }) =>
          total + quantity * price, 0), // calculate new total
      timestamp: Date.now() // perhaps you want to update this too
    }
  })
}

This uses the functional update version of the useState() hook to easily get access to the previous state value.这使用useState()挂钩的功能更新版本来轻松访问之前的 state 值。

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

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