我有一個JavaScript數組,使用array.map
呈現組件。爲了能夠使用鍵值對更容易地查找項目,我將此數組切換爲es6 Map
,並通過Map從.map
切換爲forEach
。在forEach
裏面,我調用了一個渲染方法,它返回一個React組件,但它沒有被渲染。如何渲染forEach
內的組件?forEach es6在JSX中的地圖
<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不返回任何東西,但是否意味着我不能在它裏面呈現?
如何將html字符串存儲/追加到您在forEach之後注入的變量中? – LukeS
使用['Map.prototype.values()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values)方法。 – zerkms
那麼,JSX需要一個數組?然後使用'Array.from(resultsByGuid)'並從那裏使用'.map'。 – Bergi