gpt4 book ai didi

javascript - React Native,如何将嵌套的if else转换为switch语句?

转载 作者:行者123 更新时间:2023-12-03 07:04:50 24 4
gpt4 key购买 nike

嘿,我是 react-redux 的新手,我正在努力将嵌套的 if else 语句转换为 switch 语句。谁能告诉我该怎么做?下面是我的代码

if (action.type === ADD_TO_CART) {
let addedItem = state.jeans.find((item) => item.id === action.id);
let existed_item = state.addedItems.find((item) => action.id === item.id);
if (existed_item) {
addedItem.quantity += 1;
return {
...state.jeans,
total: state.total + addedItem.price,
};
} else {
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;

return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
}

最佳答案

我猜你只是想把它从 if else 切换到 switch 对吗?

在这种情况下,我猜您可以执行以下操作:

if (action.type === ADD_TO_CART) {
let addedItem = state.jeans.find((item) => item.id === action.id);
let existed_item = state.addedItems.find((item) => action.id === item.id);
switch(existed_item){
case !undefined: {
addedItem.quantity += 1;
return {
...state.jeans,
total: state.total + addedItem.price,
};
}
default: {
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;

return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
}
}

关于javascript - React Native,如何将嵌套的if else转换为switch语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64428089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com