[英]React - Conditional rendering ( iteration from multiple arrays )
大家好,我目前在条件渲染方面存在问题。
我在状态中保存了2个数组:
this.state = {
arr_one:[1,2,3,4,5],
arr_two:[1,3,5]
};
我想用这些数组渲染divs迭代,如果arr_two中的项目存在于arr_one中,则表示条件,然后渲染不同的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
我不是过滤器! 五
预期产出:
第1项
我不是过滤器! 2
第3项
我不是过滤器! 4
第5项
我还在CodeSandBox中有我的代码演示
您可以使用includes修复条件index === this.state.arr_two[index]
:
this.state.arr_two.includes(item)
您正在将arr_one
索引与arr_one
的值进行arr_two
而且我不明白你的arr_one
有值等于0但你的输出不是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.