[英]React - Conditional rendering ( iteration from multiple arrays )
Hi guys currently I have a problem on conditional rendering in react. 大家好,我目前在条件渲染方面存在问题。
I have 2 arrays saved in state : 我在状态中保存了2个数组:
this.state = {
arr_one:[1,2,3,4,5],
arr_two:[1,3,5]
};
I want to render divs iteration with those array and the condition if items in arr_two exists in arr_one, then render the differents divs. 我想用这些数组渲染divs迭代,如果arr_two中的项目存在于arr_one中,则表示条件,然后渲染不同的div。
note : I don't want to fix this with modulus condition (%). 注意:我不想用模数条件(%)来解决这个问题。
Here's my code : 这是我的代码:
Code : 代码:
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>
)
}
}
Output : 输出:
I'm not in filter! 我不是过滤器! 1 1
I'm not in filter! 我不是过滤器! 2 2
I'm not in filter! 我不是过滤器! 3 3
I'm not in filter! 我不是过滤器! 4 4
I'm not in filter! 我不是过滤器! 5 五
Expected Output : 预期产出:
Item 1 第1项
I'm not in filter! 我不是过滤器! 2 2
Item 3 第3项
I'm not in filter! 我不是过滤器! 4 4
Item 5 第5项
I also have my code demo in CodeSandBox 我还在CodeSandBox中有我的代码演示
您可以使用includes修复条件index === this.state.arr_two[index]
:
this.state.arr_two.includes(item)
You are comparing index of arr_one
with value of arr_two
您正在将arr_one
索引与arr_one
的值进行arr_two
And I don't understand during your arr_one
have value equals 0 but your output isn't 而且我不明白你的arr_one
有值等于0但你的输出不是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.