[英]Mapping an array inside an object in React with ES6
I'm making a react-feed app, inspired by Michael's tutorial (there's also a video ) and I encountered some trouble trying to pass an array inside an array as props using Lodash's _.map function.我正在制作一个 react-feed 应用程序,灵感来自Michael 的教程(还有一个视频),我在尝试使用Lodash 的 _.map函数将数组作为道具传递给数组时遇到了一些麻烦。 This is the information I'm mapping:
这是我正在映射的信息:
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'
}
]
}
];
I'm passing to the component like this (this works):我像这样传递给组件(这有效):
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>
);
}
This works perfectly fine, dividing each "event" object这工作得很好,划分每个“事件”对象
Then I try to destructure and map the "artists:" object of each event like this:然后我尝试解构和映射每个事件的“艺术家:”对象,如下所示:
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>
);
}
This is the result I'm getting, which is close, but not what I need:这是我得到的结果,很接近,但不是我需要的:
I need to separate these further to get:我需要进一步分离这些以获得:
{artist: "Thor"} {artistPicture: "thor.jpg"}
{artist: "Loki"} {artistPicture: "loki.jpg"}
and so on...等等...
I see there's a pattern here, I just don't know how to implement it further.我看到这里有一个模式,我只是不知道如何进一步实现它。 It breaks when I try to repeat the same destructure then _.map thing.
当我尝试重复相同的解构然后 _.map 事情时,它会中断。 Can anyone please give me a hand with this, sorry for the long post.
任何人都可以帮我解决这个问题,抱歉长篇幅。
return _(this.props.events).flatMap('artists').map((artist, index)=><ItemArtist key={index} {...artist} {...props}/>).value();
Oh, I found the problem thanks to VyvIT 's comment (he deleted his comment), it's here:哦,由于VyvIT的评论(他删除了他的评论),我发现了问题,它在这里:
const { event, venue, venuePicture, when, genres, artists } = this.props.events;
_.map({artists}, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>);
"artists" shouldn't be destructured (curly brackets), should be like this: “艺术家”不应该被解构(大括号),应该是这样的:
_.map(artists, (artist, index) => <ItemArtist key={index} {...artist} {...props}/>);
Thank you so much guys!十分感谢大家!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.