forEach over es6 Map in JSX

你。 提交于 2019-12-05 01:54:15

You are correct, forEach doesn't return anything, use map instead, it will return an array of JSX components.

Map will allow you to access the key as well: resultsByGuid.map((item, key) => { })

Edit I apologize for jumping the gun and not reading that you were using a Map data structure. forEach won't render anything because you need the return value, you could implement your own Array.map like iterator:

const mapIterator = (map, cb) => {
  const agg = [];
  for(let [key, value] of map) {
    agg.push(cb(value, key));
  }
  return agg;
};

<div className='gallery__items'>
  {mapIterator(resultsByGuid, (result, index) => {
    key++;
    return this.renderGalleryItem(result, key);
  })}
</div>

Edit 2 And thanks to @zerkms for pointing out what should've been obvious to me:

<div className='gallery__items'>
  {Array.from(resultsByGuid.values()).map((result, index) => {
    key++;
    return this.renderGalleryItem(result, key);
  })}
</div>

Just a slight improvement on danday74's example using array destructuring. With options the ES6 Map:

<select>
  {
    [...options].map(([key, value]) => {
      return <option key={ key } value={ key }>{ value }</option>
    })
  }
</select>

another option, where options is an es6 Map() ..

<select>
  {
    [...options].map((entry) => {
      let key = entry[0]
      let value = entry[1]
      return <option key={ key } value={ key }>{ value }</option>
    })
  }
</select>

If you call .entries() on your map you will get an iterator object which for every key/value pair contains an array with the structure: [key, value] as mentioned here.

So you could just do:

<div className='gallery__items'>
  {resultsByGuid.entries().map((result) => {
    return this.renderGalleryItem(result[1], result[0]);
  })}
</div>

I am still wondering, if there's a simpler solution though.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!