[英]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.