forEach over es6 Map in JSX

后端 未结 4 2005
情深已故
情深已故 2021-02-19 02:22

I had a javascript array that was rendering components using array.map. I switched this array to an es6 Map in order to be able to use key-value pairs

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-19 02:28

    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;
    };
    
    
    {mapIterator(resultsByGuid, (result, index) => { key++; return this.renderGalleryItem(result, key); })}

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

    {Array.from(resultsByGuid.values()).map((result, index) => { key++; return this.renderGalleryItem(result, key); })}

提交回复
热议问题