[英]Mapping an array inside an object in React with ES6
我正在制作一個 react-feed 應用程序,靈感來自Michael 的教程(還有一個視頻),我在嘗試使用Lodash 的 _.map函數將數組作為道具傳遞給數組時遇到了一些麻煩。 這是我正在映射的信息:
const events = [
{
event: 'Gods',
venue: 'Asgard',
venuePicture: 'picture1.jpg',
when: '21:00 27/04/16',
genres: ['rock', 'funk'],
artists: [
{
artist: 'Thor',
artistPicture: 'thor.jpg'
},
{
artist: 'Loki',
artistPicture: 'loki.jpg'
}
]
},
{
event: 'Humans',
venue: 'Midgard',
venuePicture: 'picture2.jpg',
when: '21:00 27/04/16',
genres: ['jazz', 'pop'],
artists: [
{
artist: 'Human1',
artistPicture: 'human1.jpg'
},
{
artist: 'Human2',
artistPicture: 'human2.jpg'
}
]
}
];
我像這樣傳遞給組件(這有效):
renderItems(){
const props = _.omit(this.props, 'events');
return _.map(this.props.events, (event, index) => <EventsFeedItem key={index} {...event} {...props}/>);
}
render() {
return (
<section>
{this.renderItems()}
</section>
);
}
然后我嘗試解構和映射每個事件的“藝術家:”對象,如下所示:
renderArtists() {
const { event, venue, venuePicture, when, genres, artists } = this.props.events;
const props = _.omit(this.props, 'events');
return _.map({artists}, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>);
}
render() {
return (
<ul>
{this.renderArtists()}
</ul>
);
}
我需要進一步分離這些以獲得:
{artist: "Thor"} {artistPicture: "thor.jpg"}
{artist: "Loki"} {artistPicture: "loki.jpg"}
等等...
我看到這里有一個模式,我只是不知道如何進一步實現它。 當我嘗試重復相同的解構然后 _.map 事情時,它會中斷。 任何人都可以幫我解決這個問題,抱歉長篇幅。
return _(this.props.events).flatMap('artists').map((artist, index)=><ItemArtist key={index} {...artist} {...props}/>).value();
哦,由於VyvIT的評論(他刪除了他的評論),我發現了問題,它在這里:
const { event, venue, venuePicture, when, genres, artists } = this.props.events;
_.map({artists}, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>);
“藝術家”不應該被解構(大括號),應該是這樣的:
_.map(artists, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>);
十分感謝大家!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.