我正在嘗試使用 else if 陳述句從迭代物件轉換數量,然后將回傳數字添加/呈現到點。
此外,如果用戶訂購了另一個,它將被添加到現有點中。
還是有比 else if 陳述句更好的方法來做到這一點?
訂購的數量是來自物件的num并轉換為回傳點
(訂購數量為 29)= 回傳 1;
(訂購數量為276)=回傳10;
(訂購數量為522)=回傳20;
(訂購數量為1114)=回傳48;
這是我下面的代碼
const [points, setPoints] = useState(0)
const handlePoints = (value) => {
{userOrdered.map((ordered) => {
if (ordered.amount === 29) {
return setPoints(points.quantity 1);
} else if (ordered.amount === 276) {
return setPoints(points.quantity 10);
} else if (ordered.amount === 522) {
return setPoints(points.quantity 20);
} else if (ordered.amount === 1114) {
return setPoints(points.quantity 48);
}
})
}
}
<Typography onChange={handlePoints}>{points}</Typography>
uj5u.com熱心網友回復:
假設積分也被授予斷點之間的數量......newPoints宣告一個變數來累加積分,然后在回圈結束后,它只設定一次狀態。
const [points, setPoints] = useState(0)
const handlePoints = (value) => {
let newPoints = points.quantity;
userOrdered.forEach((ordered) => {
if (ordered.amount >= 29 && ordered.amount <= 275) {
newPoints = 1;
} else if (ordered.amount >= 276 && ordered.amount <= 521) {
newPoints = 10;
} else if (ordered.amount >= 522 && ordered.amount <= 1113) {
newPoints = 20;
} else if (ordered.amount >= 1114) {
newPoints = 48;
}
})
setPoints(newPoints)
}
<Typography onChange={handlePoints}>{points}</Typography>
uj5u.com熱心網友回復:
您可以采用一種更具宣告性的方法(但 IMO 的 if else 在這種大小的情況下也沒有那么糟糕):
// Must remain sorted, but you could sort it using your own sort fn if you wanted. Just saves an op.
const AMOUNT_POINTS_LOOKUP = [
{ amount: 29, points: 1 },
{ amount: 276, points: 10 },
{ amount: 522, points: 20 },
{ amount: 1114, points: 48 },
]
const handlePoints = (userOrdered) => {
const pointsToAddTotal = userOrdered.reduce((currPointsToAdd, currentOrder) => {
return currPointsToAdd (AMOUNT_POINTS_LOOKUP.findLast((rule, index) => currentOrder.amount >= rule.amount)?.points ?? 0)
}, 0)
// Ive assumed here handlePoints gets only newly added items in the form of userOrdered.
// If it was all of the items every time, you would not need to add onto `points` you'd just
// get `pointsToAddTotal` as is and set it in state.
setPoints(points => points pointsToAddTotal)
}
如果您希望能夠以一種可配置的方式(從服務器或類似的方式)定義地圖,那么這才是真正值得做的事情。
uj5u.com熱心網友回復:
考慮到特定金額的積分值是固定的,您可以創建一個靜態物件來存盤和跟蹤每個添加的訂購金額積分值 - 這也使得更新變得容易。
const ORDERED_AMOUNT_POINTS = {
29: 1,
276: 10,
522: 20,
1114: 48
}
const handlePoints = (value) => {
userOrdered.forEach((ordered) => setPoints(points.quantity
ORDERED_AMOUNT_POINTS[`${ordered.amount}`]))
}
<Typography onChange={handlePoints}>{points}</Typography>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520841.html
上一篇:Python檔案加密
下一篇:如何在陣列中的陣列中添加物件
