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

React条件渲染:仅当soldOut为false时显示FeedTag组件

解决方案

首先修正你代码里的soldOut变量赋值错误:原代码里用了productList.qty = productList.soldout,这是赋值操作,还错误地取了数组的属性(应该取当前循环的product对象),正确的判断逻辑是对比当前product的qty和soldout是否相等来确定是否售罄。

下面提供两种实现仅渲染未售罄FeedTag的方式:

方式一:在map内部添加条件判断

直接在返回FeedTag的逻辑前增加条件,未售罄时渲染组件,否则返回null:

<div>
  {productList.length > 0 &&
    productList.map((product, i) => {
      // 判断当前商品是否售罄:qty等于soldout时为售罄状态
      const isSoldOut = product.qty === product.soldout;
      // 仅当未售罄时渲染FeedTag
      if (isSoldOut) return null;
      
      return (
        <FeedTag
          key={i} {/* 给map的元素添加key属性,React需要它识别列表变化 */}
          data={product}
          name={product.headline}
          onSelect={(e) => onSelectProduct(e)}
          checked={seletedProductList.includes(product._id)}
          icon={<img src={helper.CampaignProductImagePath + product.image} alt="" />}
        />
      );
    })}
</div>

方式二:先过滤数组再渲染

先过滤出未售罄的商品,再对过滤后的数组进行map渲染,逻辑更清晰:

<div>
  {productList.length > 0 &&
    productList
      .filter(product => product.qty !== product.soldout) // 过滤出未售罄的商品
      .map((product, i) => (
        <FeedTag
          key={i}
          data={product}
          name={product.headline}
          onSelect={(e) => onSelectProduct(e)}
          checked={seletedProductList.includes(product._id)}
          icon={<img src={helper.CampaignProductImagePath + product.image} alt="" />}
        />
      ))}
</div>

内容的提问来源于stack exchange,提问作者Kyle Underhill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:05:27