我的这段代码有语法错误,我的 webpack 编译器指出我的错误在我的三元运算符中的 switch case
export function computeShipping(weight, location) {
return (dispatch, getState) => {
const state = getState();
const { shippingMatrix } = state.cart;
return shippingMatrix != null
? switch(location) {
case 'provincial':
if ( weight <= 1) {
return shippingMatrix.provincial[0].value;
}
}
: null
}
}
谁能帮帮我?
建议将不胜感激。 :)
最佳答案
好吧,编译器是完全正确的。 switch
语句是一个语句,不能作为三元运算符的操作数出现在需要表达式 的地方。
鉴于此,我无法真正说出您希望这段代码做什么,但我想您想要像这样简单的 if
条件:
export function computeShipping(weight, location) {
return (dispatch, getState) => {
const {cart: {shippingMatrix}} = getState();
if (shippingMatrix != null && location === 'provincial' && weight <= 1)
return shippingMatrix.provincial[0].value;
else
return null;
}
}
当然,您可以再次将其转换为三元:
…
return (shippingMatrix != null && location === 'provincial' && weight <= 1)
? shippingMatrix.provincial[0].value;
: null;
或者甚至将条件的静态部分移到闭包之外:
export function computeShipping(weight, location) {
return (location === 'provincial' && weight <= 1)
? (dispatch, getState) => {
const {cart: {shippingMatrix}} = getState();
return shippingMatrix && shippingMatrix.provincial[0].value;
}
: (dispatch, getState) => null;
}
关于javascript - 语法错误 : ES6 Switch case inside If else ternary Operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34219484/