大家好,我在React中的条件渲染方面遇到问题。
我在状态中保存了2个数组:
this.state = {
arr_one:[1,2,3,4,5],
arr_two:[1,3,5]
};
我想使用这些数组和条件(如果arr_two中的项目存在于arr_one中)来渲染div迭代,然后渲染不同的div。
注意:我不想使用模量条件(%)来解决此问题。
这是我的代码:
代码:
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'
}
return (
<div className="wrapper">
{
this.state.arr_one.map((item,index)=>
index === this.state.arr_two[index]?
<div key={index} className={filteredStyle}>
<p>Item {item}</p>
</div>
:
<div key={index}>
<p>I'm not in filter! {item}</p>
</div>
)
}
</div>
)
}
}
输出:
我不在过滤器中! 1
我不在过滤器中! 2
我不在过滤器中! 3
我不在过滤器中! 4
我不在过滤器中! 5
预期输出:
项目1
我不在过滤器中! 2
项目3
我不在过滤器中! 4
项目5
我也有我的代码演示 CodeSandBox
答案 0 :(得分:3)
您可以使用includes将条件index === this.state.arr_two[index]
修改为:
this.state.arr_two.includes(item)
答案 1 :(得分:0)
您正在比较索引arr_one
与值arr_two
我不知道您的arr_one
期间值是否等于0,但您的输出却不是