Immediately-invoked function expression inside JSX

后端 未结 1 1712
温柔的废话
温柔的废话 2021-01-05 15:08

I am working on the React project where I am trying to compile but cannot find why I am getting this syntax error. Specifically, what the pattern, \"{()=>{}()}\", is doin

1条回答
  •  遥遥无期
    2021-01-05 15:51

    This is Immediately-invoked function expression.

    Error With your code?

    You need to wrap the function inside (), Check this:

    {
       (() => {
          if (this.props.status === 'PENDING') {
             return (
    ); } })() }

    what the pattern, "{()=>{}()}", is doing in this context?

    Directly we can't put if/else statement or any other statement inside JSX, so for that we need to create a function and put all the logic inside that.

    As per DOC:

    if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. If a ternary expression isn't robust enough, you can use if statements outside of your JSX to determine which components should be used. Or if you prefer a more "inline" aesthetic, define immediately-invoked function expressions inside your JSX.

    Another way of writing the same code:

    render(){
        return(
            
    ....
    {this._callFun()}
    ) } _callFun(){ if (this.props.status === 'PENDING') { return (
    ); } }

    0 讨论(0)
提交回复
热议问题