admin管理员组文章数量:1402938
I am a beginner in React. I am using the json placeholder to fetch data using axios. I have two arrays in the state.
state = {
posts : [],
images : []
};
After getting the data through axios I am using set state up update the value. Now, I want it all displayed in a card. If it were just one array I would've used map to display the content. Now I want an image from the images array to be displayed with each post. How could I go about this?
I am a beginner in React. I am using the json placeholder to fetch data using axios. I have two arrays in the state.
state = {
posts : [],
images : []
};
After getting the data through axios I am using set state up update the value. Now, I want it all displayed in a card. If it were just one array I would've used map to display the content. Now I want an image from the images array to be displayed with each post. How could I go about this?
Share Improve this question asked Apr 11, 2020 at 16:06 PratyushPratyush 1831 gold badge7 silver badges15 bronze badges 2- 3 Why not bine both arrays into one and have a data object in the array that holds the post and it's image? – tomerpacific Commented Apr 11, 2020 at 16:07
-
posts.map((item, index)=> {const image = images[index]; ...})
– Yosef Tukachinsky Commented Apr 11, 2020 at 16:11
2 Answers
Reset to default 3You can create single array out of two array in this way.
const postsWithImage=this.state.posts.map(post=>{
return {
...post,
img: this.state.images.find(img=> img.id===post.imgid) // or some relation between posts and images
}
})
now further map the postsWithImage
instead of separate arrays you could bine them and loop through like this :
const renderPosts = ()=>{
return this.state.posts.map(post,index=>{
return(
<Card
postImage={post.image}
postData={post.data}
/>
)
})
}
But if you are insisting on keeping them separate than you could do a nested loop like :
const templates = {
template1: {
items: [1, 2]
},
template2: {
items: [2, 3, 4]
},
};
const App = () => (
<div>
{
Object.keys(templates).map(template_name => {
return (
<div>
<div>{template_name}</div>
{
templates[template_name].items.map(item => {
return(<div>{item}</div>)
})
}
</div>
)
})
}
</div>
);
本文标签: javascriptHow can I map through two arrays in React at the same timeStack Overflow
版权声明:本文标题:javascript - How can I map through two arrays in React at the same time? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744382623a2603579.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论