简体   繁体   English

语法错误:ES6 Switch case inside if else ternary Operator

[英]Syntax Error: ES6 Switch case inside If else ternary Operator

I am having Syntax error with this code, my webpack compiler points my error in switch case inside my ternary operator 我有这个代码的语法错误,我的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
  }
}

can anyone help me? 谁能帮我?

Suggestions will be much appreciated. 建议将不胜感激。 :) :)

Well the compiler is totally right. 那么编译器是完全正确的。 A switch statement is a statement , and cannot occur as an operand of the ternary operator where an expression is expected. switch语句是一个语句 ,不能作为期望表达式的三元运算符的操作数出现。

Given that, I cannot really tell what you expected this code to do, but I suppose you wanted something like this simple if condition: 鉴于此,我无法确切地告诉您对此代码的期望,但我认为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;
  }
}

You could turn that into a ternary again of course: 当然,你可以把它变成三元组:

    …
    return (shippingMatrix != null && location === 'provincial' && weight <= 1)
       ? shippingMatrix.provincial[0].value;
       : null;

Or even move the static part of the condition outside of the closure: 或者甚至将条件的静态部分移动到闭包之外:

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;
}

You can't use a statement (like if/switch/for) inside an expression (like ternary expressions). 您不能在表达式中使用语句(如if / switch / for)(如三元表达式)。 Same way you can't say if(for(..){..}) or if(switch(..){..}) . 同样的方式你不能说if(for(..){..})if(switch(..){..})

The easiest way to differentiate is variable assignment. 区分的最简单方法是变量赋值。 You can say var x = /*expression*/ but you can't say var x = for(...) . 你可以说var x = /*expression*/但你不能说var x = for(...) Think about things that can have value vs things that can't. 想想可以有价值的东西和不能有价值的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM