Hye,我是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切换到切换,对吗?
在这种情况下,你可以以下我猜:
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,
};
}
}
}
您的先生是对的。它应该用switch编写,因为很有可能操作类型的列表会增加,并且您会有多个案例。
应该是这样的:
s
switch(action.type) {
case 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,
};
}
default:
return state; // or something else
}
这样。。。。
switch (action.type) {
case ADD_TO_CART :
let addedItem = state.jeans.find((item) => item.id === action.id);
let existed_item = state.addedItems.find((item) => action.id === item.id);
const itemExists = existed_item ? true : false;
switch (existed_item) {
case true :
addedItem.quantity += 1;
return {
...state.jeans,
total: state.total + addedItem.price,
};
case false :
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;
return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
}
试试这个
switch(existed_item) {
case true:
addedItem.quantity += 1;
return {
...state.jeans,
total: state.total + addedItem.price,
};
case false:
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;
return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
default:
return null;
}