背景:我是一種新的反應并且正在學習它,我已經在其中制作了一些網站,但我非常懷疑我解決問題的方式。
所以在處理復雜的狀態時。例如,假設我們有一個購物車,其中有一個產品是一個物件,然后它包含一個數量鍵現在我們如何更改該數量,這將是最好的方法嗎?
例子
const [cart , setcart] = useState([
{_id: "1",
name:"product1",
quantity: 2
},
{_id: "2",
name:"product2",
quantity: 1
}
]);
假設我們需要將 id 為 2 的產品的數量更新為 5。我們是最好的方法,我的做法是。
setcart((items)=>{
const changingItem = items.find((item)=>{return item.id === "2"});
changedItem.quantity = 5;
const newCart = items;
newCart.push(changingItem);
return newCart;
})
謝謝你
uj5u.com熱心網友回復:
setCart(items => items.map(item => item.id === "2" ? {...item, quantity: 5} : item)}
uj5u.com熱心網友回復:
只是為了通知編輯串列中現有產品的這種情況,如果要添加產品,則需要檢查該專案是否不存在,然后將新產品推送到陣列中并回傳陣列的新參考。
const [cart , setcart] = useState([
{_id: "1",
name:"product1",
quantity: 2
},
{_id: "2",
name:"product2",
quantity: 1
}
]);
setcart((items)=> {
// first you need to find the index of the target product.
const itemIndex = items.find((item)=>{return item._id === "2"});
// check if the item exist.
if (itemIndex !== -1 {
// Then edit the same object inside the array.
items[itemIndex].quantity = 5;
}
// Create new instance of items array.
const newCart = [...items];
return newCart;
})
uj5u.com熱心網友回復:
setCart((items) => {
const changingItem = items.find((item)=>{return item.id === "2"});
return [...items, {...changingItem, quantity: 5}]
});
uj5u.com熱心網友回復:
這取決于它是什么型別的變數。例如,您提到是否創建映射而不是陣列,并將 _id 作為操作物件的最快方式的鍵。
setcart((items) => { items[2].quantity = 5; return {...items}; })
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/497506.html
標籤:javascript 反应 状态
下一篇:在React中動態呈現作業串列
