我正在 React 中作業,并希望根據它是否與按下“迭代”按鈕的專案匹配來迭代“購物車”陣列中物件的“數量”屬性。
我原來的解決方案是這樣的......
setCart((cart) => {
const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
if (itemMatch !== undefined) {
itemMatch.amount = itemMatch.amount 1;
} else {
cart.push(item);
}
return [...cart];
})
但是,迭代是按 2 計數的。
我的第二個解決方案是...
setCart((cart) => {
const updatedCart = cart.map((cartItem) => {
if (cartItem.name === item.name) {
return {...cartItem, amount: cartItem.amount item.amount}
} else {
return cartItem
}
})
return updatedCart;
})
此解決方案有效,但我無法弄清楚這兩者之間的區別是什么。如果有人可以幫助解釋真正有助于我理解的差異。謝謝。
uj5u.com熱心網友回復:
在第一個解決方案中,您將專案推送到已經擁有所有這些專案的現有陣列中。
offtop:第二個解決方案在不改變現有資料方面也更好。
uj5u.com熱心網友回復:
在這里,您正在做不同的事情。
假設您有一個這樣的示例輸入:
const item = { name: "abc", amount: 5 }
const cart = [
{ name: "ab", amount: 15 },
{ name: "def", amount: 10 }
]
在場景 1 中:
const setCart = ((cart) => {
/* first finding if the object which are already exist in cart array
is also exist in item object or not. */
const itemMatch = cart.find((cartItem) => cartItem.name === item.name);
// if item found increase amount by 1
if (itemMatch !== undefined) {
itemMatch.amount = itemMatch.amount 1;
} else { // if item not found add that item to array
cart.push(item);
}
// and returning it
return [...cart];
})
// output
/* [
{ name: 'ab', amount: 15 },
{ name: 'def', amount: 10 },
{ name: 'abc', amount: 5 }
] */
在場景 2 中:
const setCart = ((cart) => {
// looping into the cart array and searching if item exist in cart or not
const updatedCart = cart.map((cartItem) => {
// if item which are in cart is also exist
if (cartItem.name === item.name) {
// return all oder cart item, and update the amount
return {...cartItem, amount: cartItem.amount item.amount }
} else {
// return the cart item as it is
return cartItem
}
})
// returning the cart array
return updatedCart;
})
// output
/* [
{ name: 'ab', amount: 15 },
{ name: 'def', amount: 10 }
] */
在場景 2 中,
您永遠無法將新專案添加到購物車中,因為您正在回圈進入購物車專案并檢查專案是否存在(如果存在則更新購物車,如果不存在則按原樣回傳購物車專案)。
在場景 1 中,
you're first finding if the cart item is exist or not, and ensure if the item is already exist in cart just update the amount, and if not exist then add item to cart. (This works in real Scenario)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/353993.html
標籤:javascript 反应 迭代
