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
相关产品推荐
相关产品推荐

