You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中如何编写无else的三元运算符,实现无数据时隐藏整个区块

解决方案

调整思路

  • 原有逻辑是无论是否有数据都会渲染Prime区块的外层容器,无数据时仅替换区块内容为提示文本
  • 调整后新增最外层数据校验:只有memberships为有效非空数组时才渲染整个<section>区块,否则直接返回null隐藏整个区块
  • 移除原有的无数据提示分支,无需再渲染提示文本

修改后完整代码

const WpPrime = ({ translate, memberships, otherDetails, selectedTemplate, }) => {
  // 数据校验不通过直接返回null,隐藏整个Prime区块
  if (!(Array.isArray(memberships) && memberships.length > 0)) return null;

  // 有数据时正常渲染全部内容
  return (
    <section className="prime-section">
      <p className="section-title">
        {(otherDetails.section_title && otherDetails.section_title.prime) || translate('Premier')}
      </p>
      {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>
        ))
      }
    </section>
  );
};

核心改动说明

  • 新增前置判断逻辑:只要memberships不是数组或数组为空,组件直接返回null,浏览器不会渲染任何相关内容,整个Prime区块完全隐藏
  • 原有的有数据渲染逻辑完全保留,没有修改原有展示规则,不会影响正常数据的展示效果
  • 移除了原来三元表达式的无数据分支,不需要再展示「无可用数据」提示

内容的提问来源于stack exchange,提问作者XD Sauaame

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 14:36:05