簡體   English   中英

如何使用 map 在 jsx 中渲染某個項目一次?

[英]how to render a certain item once in jsx using map?

如何在 map function 中渲染和項目一次? 我有一個對象數組,我只想將顏色值渲染一次到另一個組件中,我嘗試將顏色推入一個數組並對其進行檢查,但由於它在循環內,它會立即被添加,並且這個檢查會失敗,關鍵是我不希望相同的顏色被渲染兩次,如果發現那么只有一次......這種情況有什么好的解決方案嗎?

 const items =[{car: 'bmw', color: 'black'}, {car: 'opel', color:'black'}, {car:'landrover',color:'red'}] {items.map((item, i) => { let arr = []; //arr.push(items[i].color); return ( <React.Fragment> {arr.includes(items[i])? undefined: <colors img={items[i]?.color} /> } <items key={item.id} Car={item.car} /> </React.Fragment> ); })} // Expected result // black color component // 'bmw' // 'opel' // red color component // 'landrover'

我建議您首先按顏色對項目進行排序,然后僅在顏色與前一個項目不同時才渲染顏色組件:

items
  .sort((a, b) => a.color.localeCompare(b.color))
  .map((item, index, sortedItems) => {
    const colorChanged = !index || item.color !== sortedItems[index - 1].color
    
    return (
      <>
        { colorChanged && <colors img={items[i]?.color} /> }
        <items key={item.id} Car={item.car} />
      </>
    )
  })

編輯:由於index是 integer >= 0,當index === 0時, !index將准確評估為真。

const itemColors = items
  .map(({ color }) => color) // create array of colors
  .filter((value, index, self) => self.indexOf(value) === index) // remove duplicates

// do your rendering here

或者使用lodash

 const items =[ {car: 'bmw', color: 'black'}, {car: 'opel', color:'black'}, {car:'landrover',color:'red'} ] //Expected Outcome /* [ { color: 'black' cars: ['bmw','opel'] }, { color: 'black' cars: ['bmw','opel'] } ] */ const finalResult = items.reduce((acc, cur, arr) => { let res = [...acc]; const matchIndex = res.findIndex(obj => obj.color === cur.color); if (matchIndex === -1) { res.push({ color: cur.color, cars: [cur.car] }) } else { res[matchIndex].cars.push(cur.car) } acc = res; return acc; }, [] ) console.log(finalResult); finalResult.forEach(colorObject => { colorObject.cars.forEach(car => { console.log( `Your Component with Color ${colorObject.color} and Car ${car}` ); }) })

所以你需要先過濾顏色值並制作一個沒有重復顏色的數組。 然后你需要通過顏色過濾來渲染汽車名稱。 沒有任何第三方庫的簡單方法是這樣的:

const colors = items
   .map((data) => data.color)
   .filter((v, i, s) => s.indexOf(v) === i) 

{colors.map((color) => (
    <div>
        {color}
        {items.filter(item => item.color === color).map((item)=> (
            <>{item.car}</>
        )}
    </div>
)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM