首页 > 解决方案 > 如何使用 ReactJs 在没有 else 的情况下编写三元运算符?

问题描述

目前在我的代码中,如果有数据,我正在显示详细信息,例如(年份、标题、注册和位置),如果没有数据,那么我在 Prime 部分下显示没有可用的数据消息,现在我想隐藏整个部分的详细信息,如果没有可用数据。

 const WpPrime = ({
      translate, memberships, otherDetails, selectedTemplate,
    }) => (
      <section className="prime-section">
        <p className="section-title">
          {(otherDetails.section_title
            && otherDetails.section_title.prime)
        || translate('Premier')}
        </p>
        {Array.isArray(memberships) && memberships.length > 0 ? (
          memberships
            .sort((a, b) => b.year - a.year)
            .map(item => (
              <div key={item.year || item.title} className={`two-column-section date-alignment-${otherDetails && otherDetails.date_alignment}`}>
                <p className="section-sub-title" style={{ color: getColor(selectedTemplate) }}>
                  {item.year}
                </p>
                <div className="section-description">
                  <p className="section-title-description" style={{ color: getColor(selectedTemplate), fontWeight: '700' }}>
                    {item.title}
                  </p>
                  <p>
                    {item.registration ? ` ${item.registration}` : ''},
                    &nbsp;{item.location}
                  </p>
                </div>
              </div>
            ))
        ) : (
          <p className="section-description">{translate('dataNotAvailable')}</p>
        )}
      </section>
    );

标签: reactjs

解决方案


你可以在 else 部分使用null或 <></> (React Fragment 标签)。

{ your_condition ? render_what_you_want : null}

或者

{ your_condition ? render_what_you_want : <></>}

推荐阅读