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

React映射数组时,如何仅渲染首个满足条件的删除按钮?

解决方法

先找到第一个满足sector.properties.length === 0的元素索引,之后在遍历数组时,只有当前元素的索引和这个第一个索引匹配时,才渲染删除按钮。

修改后的代码如下:

// 获取第一个符合条件的sector的索引
const firstEmptySectorIndex = data.sectors.findIndex(sector => sector.properties.length === 0);

{data.sectors.map((sector, index) => (
    <SingleLineCell
      key={`${data.productName}Product${index}`}
    >
      {/* 仅当当前索引等于第一个符合条件的索引时渲染按钮 */}
      {index === firstEmptySectorIndex && sector.properties.length === 0 && (
        <button
          type="button"
          onClick={() => 
            showModal('DeleteData', {
              form: data,
              onConfirmDelete: () => {
                onConfirmDelete(data);
              }
            })
          }
        >
          <IconDelete responsive />
          <span className="sr-only">Delete {data.productName} Product</span>
        </button>
      )}
    </SingleLineCell>
  ))}

逻辑说明

  • findIndex会返回数组中第一个满足条件的元素索引,若没有符合条件的元素则返回-1,此时不会渲染任何按钮,符合预期。
  • 遍历数组时,只有当前元素索引与第一个符合条件的索引匹配,同时确认该sector确实满足条件(规避极端异常情况),才会渲染按钮,以此保证仅显示第一个符合要求的按钮。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:15:43