简体   繁体   English

如何使用 map 在 jsx 中渲染某个项目一次?

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

How to render and item once In a map function?如何在 map function 中渲染和项目一次? I have and array of objects and I want to render the color value only once into another component, I tried to push the color in to an array and checked against it but since it is inside the loop it is getting added instantly,and this check will fail, the point is I don't want the same color to be rendered twice, if found then only once… any good solution for this case?我有一个对象数组,我只想将颜色值渲染一次到另一个组件中,我尝试将颜色推入一个数组并对其进行检查,但由于它在循环内,它会立即被添加,并且这个检查会失败,关键是我不希望相同的颜色被渲染两次,如果发现那么只有一次......这种情况有什么好的解决方案吗?

 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'

I'd suggest you first sort your items by color and then only render the color component when the color differs from the previous item:我建议您首先按颜色对项目进行排序,然后仅在颜色与前一个项目不同时才渲染颜色组件:

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} />
      </>
    )
  })

Edit: As index is an integer >= 0, !index will evaluate to true exactly when index === 0 does.编辑:由于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

Or using lodash或者使用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}` ); }) })

So You will need to filter the color value first and make an array of no duplicate color.所以你需要先过滤颜色值并制作一个没有重复颜色的数组。 Then you need to render the cars name by filtering by the color.然后你需要通过颜色过滤来渲染汽车名称。 The simple approach without any third party library will be like this:没有任何第三方库的简单方法是这样的:

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