useState 删除状态包含对象中的数组元素

useState delete array element in the state containing object

我的状态 orderDetail 包含 orderDetail json

我正在获取要在函数中删除的订单的 _id,例如 _id: 60f1ab20891ced4818b5ea87,

现在我想从 orderdetail 中的订单数组中删除此订单并更新状态。

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',
}

我所做的是克隆状态,然后使用 for 循环查找订单的索引,然后删除克隆中的索引元素,然后将状态更新为克隆。还有其他更少计算的方法吗?

您需要使用 orders 数组 filtered 设置一个新对象以及一个新的 totalPrice.

例如

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

这使用 functional update 版本的 useState() 挂钩来轻松访问先前的状态值。