简体   繁体   English

通过一次数据迭代创建多个项目

[英]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? 如果不是-反应是否以某种方式优化了多次通过?

webpackbin webpackbin

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.

相关问题 创建一个函数,该函数返回一个数组,其中包含由两个数组或一个数组和多个单个项构建的唯一项 - Create a function that returns an array with unique items built from two arrays or an array and multiple single items 从 JSON 数据为多个项目创建复杂表 - create complex table from the JSON data for multiple items 我可以从多个数据源创建单个HighCharts图(在这种情况下为多个GoogleSheets) - Can I Create a Single HighCharts Graph from Multiple Data Sources (Multiple GoogleSheets in this case) jQuery在.each迭代中删除多个最后一项 - jQuery remove multiple last items on .each iteration 如何从单个数组创建多个数组? - How to create multiple array from single array? 如何从多个数组创建单个对象 - How to create a single object from multiple arrays 使用单个正则表达式捕获多个列表中的项目 - Capturing items from multiple lists using a single regex 在 javascript 中从单个单个 JSON 响应创建多个字典? - Create Multiple dictionary from single single JSON response in javascript? 多个forms数据单表提交 - Single form submission of data from multiple forms 使用单个数据模型架构创建具有不同名称的多个集合 - Using a single Data Model Schema to create multiple collections with different names
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM