我的狀態 orderDetail 包含 orderDetail json
我正在獲取要在函式中洗掉的訂單的_id,例如_id:60f1ab20891ced4818b5ea87,
現在我想從 orderdetail 中的 orders 陣列中洗掉這個訂單并更新狀態。
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 回圈查找訂單的索引,然后在克隆中洗掉該索引元素,然后將狀態更新為克隆。還有其他更少的計算方法嗎?
uj5u.com熱心網友回復:
您需要做的是設定一個新物件,該物件過濾了orders陣列以及一個新的.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
}
})
}
這使用鉤子的功能更新版本useState()來輕松訪問之前的狀態值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/407179.html
標籤:
