19

我有一个 javascript 数组,它使用array.map. 我将此数组切换为 es6 Map,以便能够使用键值对更轻松地查找项目,并在 Map 上从 a 切换.map到 a 。forEach在里面forEach我调用了一个返回 React 组件的渲染方法,但它没有被渲染。如何在forEach?

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

这是 renderGalleryItem 方法:

renderGalleryItem = (item, index) => {
    const { gridItemSelected, itemThumbnailRequested } = this.props;
    return (
        <GalleryItem
            key={index}
            item={item}
            onClick={gridItemSelected}
            fetchThumbnailFunc={itemThumbnailRequested}
        />
    );
};

我知道 forEach 不会返回任何内容,但这是否意味着我无法在其中渲染?

4

4 回答 4

14

你是对的,forEach不返回任何东西,map而是使用它,它将返回一个 JSX 组件数组。

Map 也将允许您访问密钥:resultsByGuid.map((item, key) => { })

编辑我很抱歉跳枪并没有读到您正在使用Map数据结构。forEach不会渲染任何东西,因为您需要返回值,您可以实现自己的Array.map迭代器:

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>

编辑 2感谢@zerkms 指出对我来说应该很明显的事情:

<div className='gallery__items'>
  {Array.from(resultsByGuid.values()).map((result, index) => {
    key++;
    return this.renderGalleryItem(result, key);
  })}
</div>
于 2016-02-23T23:55:04.287 回答
14

只是对 danday74 使用数组解构的示例略有改进。使用选项 ES6 Map:

<select>
    {[...options].map(([key, value]) => (
        <option key={key} value={key}>
            {value}
        </option>
    ))}
</select>;
于 2018-01-16T10:15:33.933 回答
7

另一种选择,optionses6 Map() ..

<select>
  {
    [...options].map((entry) => {
      let key = entry[0]
      let value = entry[1]
      return <option key={ key } value={ key }>{ value }</option>
    })
  }
</select>
于 2017-06-09T11:59:58.783 回答
0

如果您.entries()在地图上调用,您将获得一个迭代器对象,该对象对于每个键/值对都包含一个具有以下结构的数组:如此[key, value]所述。

所以你可以这样做:

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

我仍然想知道,如果有一个更简单的解决方案。

于 2017-03-20T00:02:39.853 回答