如何遍历数组并将每3个项目添加到新的Div中

时间:2019-05-19 12:29:08

标签: reactjs twitter-bootstrap iterator

所以我有一个包含100个对象的数组,这些对象是手机的描述。现在,我要做的是在类名为的新div中将页面上的所有对象与每3个项目一起显示。

我尝试使用for-of循环,但是我无法做出仅添加3个项目,然后为其他3个项目创建新的div的逻辑。

这是我要实现的(JSX):

<div className="row">
  <Mobile deviceName={mobile.DeviceName} />
  <Mobile deviceName={mobile.DeviceName}/>
   <Mobile deviceName={mobile.DeviceName}/>
 </div>
 <div className="row">
    <Mobile deviceName={mobile.DeviceName} />
    <Mobile deviceName={mobile.DeviceName}/>
    <Mobile deviceName={mobile.DeviceName}/>
 </div>
 <div className="row">
   <Mobile deviceName={mobile.DeviceName} />
   <Mobile deviceName={mobile.DeviceName}/>
   <Mobile deviceName={mobile.DeviceName}/>
  </div>

这是我到目前为止所做的

    {
    this.state.mobiles.map(mobile => {
    return (
      <div className="col col-md-4 col-sm-1">
       < Mobile 
       key={mobile.DeviceName}
       deviceName={mobile.DeviceName}
       />
      </div> )
     })
   }

1 个答案:

答案 0 :(得分:0)

也许您可以先将100个对象的数组格式化为嵌套的数组结构,然后再映射通过数组?

renderMobiles = () => {
  let formattedArray = []
  let arrayOfThrees = []
  this.state.mobiles.forEach((mobile) => {
    if(arrayOfThrees.length < 3) {
    // If there is less than 3 items in the arrayOfThrees then push the mobile object into it
      arrayOfThrees.push(mobile)
    } else {
      // If there is more than 3 items in the arrayOfThrees
      // 1. Push the arrayOfThrees into the formattedArray (nested array)
      formattedArray.push(arrayOfThrees)
      // 2. Reset the arrayOfThrees with new mobile object (ie. it will go from 3 objects to 1 new object)
      arrayOfThrees = [mobile]
    }
  })

  formattedArray = [...formattedArray, arrayOfThrees]

  return formattedArray.map(arrayOfThrees => {
    let rowContent = arrayOfThrees.map(mobile => <Mobile deviceName={mobile.DeviceName} />)
    return(
      <div className="row">
        {rowContent}
      </div>
    )
  })
}