als*_*ion 12 javascript foreach jsx
我有一个使用渲染组件的javascript数组array.map.我将此数组切换为es6 Map,以便能够使用键值对更轻松地查找项目,并通过Map 从a切换.map到a forEach.在forEach我内部调用一个返回React组件的render方法,但它没有被渲染.如何在里面渲染组件forEach?
<div className='gallery__items'>
{resultsByGuid.forEach((result, index) => {
key++;
this.renderGalleryItem(result, key);
})}
</div>
Run Code Online (Sandbox Code Playgroud)
这是renderGalleryItem方法:
renderGalleryItem = (item, index) => {
const { gridItemSelected, itemThumbnailRequested } = this.props;
return (<GalleryItem key={index}
item={item}
onClick={gridItemSelected}
fetchThumbnailFunc={itemThumbnailRequested}
/>);
};
Run Code Online (Sandbox Code Playgroud)
我明白forEach不返回任何东西,但这是否意味着我无法在其中渲染?
Rob*_* M. 11
你是对的,forEach不返回任何东西,map而是使用它,它将返回一个JSX组件数组.
地图也允许您访问密钥: 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>
Run Code Online (Sandbox Code Playgroud)
编辑2感谢@zerkms指出应该对我来说显而易见的事情:
<div className='gallery__items'>
{Array.from(resultsByGuid.values()).map((result, index) => {
key++;
return this.renderGalleryItem(result, key);
})}
</div>
Run Code Online (Sandbox Code Playgroud)
小智 8
使用数组解构的danday74示例略有改进.使用选项ES6 Map:
<select>
{
[...options].map(([key, value]) => {
return <option key={ key } value={ key }>{ value }</option>
})
}
</select>
Run Code Online (Sandbox Code Playgroud)
另一个选项,其中options是es6 Map()..
<select>
{
[...options].map((entry) => {
let key = entry[0]
let value = entry[1]
return <option key={ key } value={ key }>{ value }</option>
})
}
</select>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17027 次 |
| 最近记录: |