gpt4 book ai didi

javascript - 如何同时映射 React 中的两个数组?

转载 作者:行者123 更新时间:2023-12-02 02:55:49 26 4
gpt4 key购买 nike

我是 React 的初学者。我正在使用 json 占位符通过 axios 获取数据。我在该州有两个数组。

state = {
posts : [],
images : []

};

通过 axios 获取数据后,我使用 set state up 更新值。现在,我希望将其全部显示在卡片中。如果它只是一个数组,我会使用 map 来显示内容。现在我希望图像数组中的图像随每个帖子一起显示。我该怎么办?

最佳答案

您可以通过这种方式从两个数组中创建单个数组。

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
}

})

现在进一步映射 postsWithImage

关于javascript - 如何同时映射 React 中的两个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com