[英]Create multiple items from a single data iteration
i have the following react code: 我有以下反应代码:
function Hello () {
let items = ["red","green","blue","#369","#fed","dad","grey","wheat","#a34","#d00"];
return (
<div>
<ul>
{items.map((v)=><li style={{border: `1px solid ${v}`, width: "10px", height: "10px", "border-radius": "50%", display: "inline-block"}}></li>)}
</ul>
<ul>
{items.map((v)=><li style={{border: `1px solid ${v}`}}>{v}</li>)}
</ul>
</div>
)
}
as you can see, I'm iterating twice in order to create both lists, however, since the data they use is the same - I'd like a way to create it with a single pass. 如您所见,为了创建两个列表,我要进行两次迭代,但是,由于它们使用的数据是相同的-我想一种通过一次创建的方法。
Is it even possible? 可能吗? if not - does react optimizes the multiple pass in some way? 如果不是-反应是否以某种方式优化了多次通过?
Solution using a for of instead of Array.map 使用for代替Array.map的解决方案
function Hello () {
const items = ["red","green","blue","#369","#fed","dad","grey","wheat","#a34","#d00"];
const listOne = []
const listTwo = []
for (let v of items) {
listOne.push(<li style={{border: `1px solid ${v}`, width: "10px", height: "10px", "border-radius": "50%", display: "inline-block"}}></li>)
listTwo.push(<li style={{border: `1px solid ${v}`}}>{v}</li>)
}
return (
<div>
<ul>
{listOne}
</ul>
<ul>
{listTwo}
</ul>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.