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

React条件渲染问题:多数组遍历匹配渲染不同Div

解决React条件渲染中数组元素匹配的问题

嘿,我看到你在这个React条件渲染的场景里踩了个小坑,咱们一步步来把它搞定:

原代码的核心问题

你当前的判断逻辑和属性使用都有问题:

  • 错误的判断条件:index === this.state.arr_two[index]是在拿arr_one的元素索引和arr_two对应索引的元素值做比较,比如arr_one[0]是1,但你实际在判断0 === arr_two[0](也就是0===1),这显然永远不成立,所以所有元素都走了else分支。
  • 样式属性误用:你把样式对象传给了className属性,但className需要的是CSS类名字符串,内联样式应该通过style属性传递。

正确的实现方案

我们需要准确判断arr_one中的每个元素是否存在于arr_two中,这里推荐用Set来优化查找性能(数组较大时更明显),也可以直接用数组的includes方法。

修改后的完整代码

class TestComp extends React.Component {
  constructor(props) {
    super(props);
    this.state = { arr_one:[1,2,3,4,5], arr_two:[1,3,5] };
  }

  render() {
    const filteredStyle = { background:'red' };
    // 把arr_two转换成Set,提升元素查找效率
    const includedItems = new Set(this.state.arr_two);

    return ( 
      <div className="wrapper">
        {this.state.arr_one.map((item, index) => 
          includedItems.has(item) ? 
            <div key={index} style={filteredStyle}>
              <p>Item {item}</p>
            </div>
            : 
            <div key={index}>
              <p>I'm not in filter! {item}</p>
            </div>
        )}
      </div>
    )
  }
}

关键修改说明

  • 修正判断逻辑:用includedItems.has(item)替代原有的索引比较,精准判断当前元素是否在目标数组中
  • 修复样式属性:把className={filteredStyle}改成style={filteredStyle},符合React内联样式的传递规则
  • 可选的简化写法:如果你的数组规模很小,也可以直接用this.state.arr_two.includes(item)替代includedItems.has(item),功能完全一致。

这样修改后,就能得到你想要的预期输出:

Item 1
I'm not in filter! 2
Item 3
I'm not in filter! 4
Item 5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:23:11