以这种方式使用简写if / else语句是错误的

时间:2017-08-12 21:03:14

标签: reactjs

我正在学习反应,我正在努力提高代码的质量。在下面的示例中,我有一个纯函数,另一个组件使用它来返回用户列表。在我的代码中,我使用简写if / else语句。这是写这样的东西的正确方法,还是有一种更清晰的可读性和错误最小化方式。感谢您的任何见解。

function CandidateList(props) {
  return (
    <Row className="candidate-white-background">
      <Col xs={3} sm={2}>
        {
          props.candidate.profileAvatarURL
          ? <Image className="img-responsive" src={props.candidate.profileAvatarURL} rounded />
          : <Alert bsStyle="danger" className="text-center nothing-in-section-alert-box">
              No Profile Image
            </Alert>
        }
      </Col>
      <Col xs={9} sm={10}>
        { props.candidate.name ? <Link to={`/admin/candidate_profile/${props.candidate.userId}`}> <h3 className="candidate-profile-name">{(props.candidate.name.first + ' ' + props.candidate.name.last)}</h3></Link> : 'No name' }

        { props.candidate.professionalOverview ? <h4>{(props.candidate.professionalOverview.currentCompany + ' ' + props.candidate.professionalOverview.currentTitle)}</h4> : 'Mobile missing' }
        { props.candidate.summary ? <p>{props.candidate.summary.substring(0, 300)}</p> : 'No summary' }
        { props.candidate.contact ? <p><FontAwesome className="fa-fw" name="mobile"/>{props.candidate.contact.mobile}</p> : <p><FontAwesome className="fa-fw" name="mobile" />N/A</p> }
        { props.candidate.address ? <p><FontAwesome className="fa-fw" name="map-marker"/>{props.candidate.address.fullAddress}</p> : <p><FontAwesome className="fa-fw" name="map-marker" />N/A</p> }
      </Col>
    </Row>
  );
}

1 个答案:

答案 0 :(得分:1)

速记被称为“三元表达”,它完全可以接受。至于“正确的方式”,我们知道编程时确实没有“正确的方法”。您应该使用使代码更易读且易于理解的模式。我个人认为三元表达式非常简单,并且使代码易于推理。

我个人喜欢把我的三元组放进去

{ this.state.someProp 
 ? <AThing/> 
 : <SomeOtherThing/> 
}

这样我可以很容易地看到什么是什么。这完全取决于你自己的个人风格。

相关问题