Javascript 如何在React中同时映射两个数组?
我是英语初学者。我正在使用json占位符使用axios获取数据。我在州里有两个数组Javascript 如何在React中同时映射两个数组?,javascript,reactjs,react-redux,Javascript,Reactjs,React Redux,我是英语初学者。我正在使用json占位符使用axios获取数据。我在州里有两个数组 state = { posts : [], images : [] }; 通过axios获取数据后,我将使用设置状态设置更新值。 现在,我想把它全部显示在一张卡片上。如果只是一个数组,我会用map来显示内容。现在,我希望在每篇文章中显示图像数组中的图像。我怎样才能做到这一点呢?您可以将它们组合起来,像这样循环: const rend
state = {
posts : [],
images : []
};
通过axios获取数据后,我将使用设置状态设置更新值。
现在,我想把它全部显示在一张卡片上。如果只是一个数组,我会用map来显示内容。现在,我希望在每篇文章中显示图像数组中的图像。我怎样才能做到这一点呢?您可以将它们组合起来,像这样循环:
const renderPosts = ()=>{
return this.state.posts.map(post,index=>{
return(
<Card
postImage={post.image}
postData={post.data}
/>
)
})
}
constrenderposts=()=>{
返回this.state.posts.map(post,index=>{
返回(
)
})
}
但如果您坚持将它们分开,则可以执行嵌套循环,如:
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>
);
const模板={
模板1:{
项目:[1、2]
},
模板2:{
项目:[2、3、4]
},
};
常量应用=()=>(
{
Object.key(templates).map(template_name=>{
返回(
{模板名称}
{
模板[模板名称].items.map(item=>{
返回({item})
})
}
)
})
}
);
您可以将它们组合在一起并像这样循环,而不是单独的阵列:
const renderPosts = ()=>{
return this.state.posts.map(post,index=>{
return(
<Card
postImage={post.image}
postData={post.data}
/>
)
})
}
constrenderposts=()=>{
返回this.state.posts.map(post,index=>{
返回(
)
})
}
但如果您坚持将它们分开,则可以执行嵌套循环,如:
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>
);
const模板={
模板1:{
项目:[1、2]
},
模板2:{
项目:[2、3、4]
},
};
常量应用=()=>(
{
Object.key(templates).map(template_name=>{
返回(
{模板名称}
{
模板[模板名称].items.map(item=>{
返回({item})
})
}
)
})
}
);
您可以用这种方法从两个数组中创建一个数组
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您可以用这种方法从两个数组中创建一个数组
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为什么不将两个数组合并为一个数组,并在数组中拥有一个保存post及其图像的数据对象?
posts.map((item,index)=>{const image=images[index];…})
为什么不将两个数组合并为一个数组,并在数组中拥有一个保存post及其图像的数据对象?posts.map((项目,索引)=>{const image=images[index];…})