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
Add a ment  | 

2 Answers 2

Reset to default 3

You 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