我有以下反应代码:
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>
)
}
正如你所看到的,我正在迭代两次以创建两个列表,但是,因为他们使用的数据是相同的 - 我想要一种通过一次传递创建它的方法。
甚至可能吗?如果不是 - 是否会以某种方式对多次传递做出反应?
答案 0 :(得分:0)
使用for 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>
)
}