ReactJS syntax for if else with map function in br

2020-07-19 01:24发布

I'm new to React and struggling with the syntax. I have this block as a div inside my render function. Every change I make goes from one syntax error or another or just doesn't work.

<div className="skillSection">
{        
    if (this.state.challengeChoices.length < 0) {                               
         this.state.challengeChoices.map((para2, i) =>
             <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
    }
    else {
        return <div>Hello world</div>
    }   
}   
</div>

3条回答
Luminary・发光体
2楼-- · 2020-07-19 02:08

jsx doesn't support conditional statement, but it support ternary operator, so you can do it like this:

<div className="skillSection">
{  this.state.challengeChoices.length < 0 ? (                               
     this.state.challengeChoices.map((para2, i) =>
         <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)) : ( <div>Hello world</div>)
}  
</div>
查看更多
做个烂人
3楼-- · 2020-07-19 02:16

I like the following approach when it's just an if statement:

<div className="skillSection">
    {this.state.challengeChoices.length < 0 && 
        <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />
    }
</div>

Of course, if/else has many options:

// Use inline if/else with some more readable spacing/indentation
render() {
    return (
        <div className="skillSection">
            {this.state.challengeChoices.length < 0 ? (
                <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />
            ) : (
                <div>False</div>
            )}
        </div>
    )
}

// Define as variable
render() {
    let dom = <div>False</div>;
    if (this.state.challengeChoices.length < 0) {
        dom = <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />;
    }

    return (
        <div className="skillSection">
            {dom}
        </div>
    )
}

// Use another method
getDom() {
    if (this.state.challengeChoices.length < 0) {
        return <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />;
    }

    return <div>False</div>;
}

render() {
    return (
        <div className="skillSection">
            {this.getDom()}
        </div>
    )
}
查看更多
forever°为你锁心
4楼-- · 2020-07-19 02:27

Recommend making a function:

renderSkillSection: function(){
    if (this.state.challengeChoices.length < 0) {                               
        return this.state.challengeChoices.map((para2, i) =>
             <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
    }
    else {
        return <div>Hello world</div>
    }   
},

render: function(){
  return (<div className="skillSection">
    {this.renderSkillSection()}   
  </div>)
}
查看更多
登录 后发表回答