Failed to compile, Unexpected token if in ReactJS

后端 未结 2 1855
情深已故
情深已故 2020-12-22 04:29

I cant seem to get this simple function to work basically my markup is like so(simplified)

{ loading || Object.keys(product).length <= 0 ? \'loading\' :
          


        
相关标签:
2条回答
  • 2020-12-22 04:48

    JSX doesn't allow if statement within the return function. But you are allowed to use ternary expressions

    { loading || Object.keys(product).length <= 0 ? 'loading' :
      <div>
        {(condition here)? <div>Hello World</div>: null}
        <ProductPictureWidget mainPic={product.pic_url} />
        <ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>
      </div>
    }
    

    However if you want to make use of if statement there is an alternative way to do it, i.e to call a function within which you use the if-else statements

    conditionalRender() {
       if(condition) {
          return <div>Hello</div>
       } else {
          return null
      }
    }
    
    { loading || Object.keys(product).length <= 0 ? 'loading' :
      <div>
        {this.conditionalRender()}
        <ProductPictureWidget mainPic={product.pic_url} />
        <ProductOptionsWidget product={product} activeProps={activeProps} selectProductOption={this.selectProductOption}/>
      </div>
    }
    
    0 讨论(0)
  • 2020-12-22 04:50

    JSX only allows expressions, not statements. The ternary operator is an expression. if starts an if statement. You can see why an if statement wouldn't work by looking at the compiled JavaScript (with the if statement removed):

    {
      loading || Object.keys(product).length <= 0 ? 'loading' : React.createElement(
        'div',
        null,
        React.createElement(ProductPictureWidget, { mainPic: product.pic_url }),
        React.createElement(ProductOptionsWidget, { product: product, activeProps: activeProps, selectProductOption: undefined.selectProductOption })
      );
    }
    

    JSX amounts to function calls and object declarations. If the if statement were compiled, it would yield invalid JavaScript:

    {
      loading || Object.keys(product).length <= 0 ? 'loading' : React.createElement(
        'div',
        null,
        if(){ }, // This is **invalid** JavaScript!!
        React.createElement(ProductPictureWidget, { mainPic: product.pic_url }),
        React.createElement(ProductOptionsWidget, { product: product, activeProps: activeProps, selectProductOption: undefined.selectProductOption })
      );
    }
    
    0 讨论(0)
提交回复
热议问题