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

React中仅当is_active属性存在时执行filter配合map的实现方法

问题原因

原代码的过滤逻辑只判断is_active值是否等于1,当元素不存在is_active属性时,data.is_active === 1 会返回false,这类元素会被全部过滤掉,最终传给map的是空数组,所以没有返回内容。

解决方案

方案1:单个元素无is_active属性时直接保留

调整filter的判断规则,不存在is_active属性的元素直接放行,仅对存在该属性的元素做值校验,同时添加边界判断避免props.types为空时报错:

props.types?.filter(data => {
  // 元素不存在is_active属性,直接保留
  if (!('is_active' in data)) {
    return true
  }
  // 存在该属性时,仅保留值为1的元素
  return data.is_active === 1
}).map((data, index) => {
  // 原有业务逻辑代码
}) ?? []

方案2:整个数组无is_active属性时完全跳过过滤

如果你的需求是只有数组里存在带is_active属性的元素时才执行过滤,否则所有元素全部保留直接走map,可以用如下逻辑:

const hasActiveField = props.types?.some(data => 'is_active' in data) ?? false
const renderList = hasActiveField 
  ? props.types.filter(data => data.is_active === 1)
  : props.types || []

renderList.map((data, index) => {
  // 业务逻辑代码
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:06:03