简体   繁体   中英

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

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.

Given that, I cannot really tell what you expected this code to do, but I suppose you wanted something like this simple if condition:

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). Same way you can't say if(for(..){..}) or if(switch(..){..}) .

The easiest way to differentiate is variable assignment. You can say var x = /*expression*/ but you can't say var x = for(...) . Think about things that can have value vs things that can't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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