Javascript 根据接收到的数据按特定顺序呈现不同的子组件
我目前正在使用Javascript 根据接收到的数据按特定顺序呈现不同的子组件,javascript,reactjs,Javascript,Reactjs,我目前正在使用wagtailv2api为我的react前端生成动态页面内容。数据如下: "content": [ { "type": "grid", "value": { "grid": [ { "title": "Fast and
wagtailv2api
为我的react前端生成动态页面内容。数据如下:
"content": [
{
"type": "grid",
"value": {
"grid": [
{
"title": "Fast and reliable",
"subtitle": "Hello there testing this out man",
"button_page": 3,
"image": 2
}
]
},
"id": "e5e370e2-aef0-4ef8-b34f-c4bf9db16e22"
} ,
{
"type": "not-grid",
"value": {
"grid": [
{
"title": "Fast and reliable",
"subtitle": "Hello there testing that out man",
"button_page": 3,
"image": 2
}
]
},
"id": "e5e370e2-aef0-4ef8-b34f-c4bf9db16e12"
}
]
<Fragment>
<Grid/>
<NotGrid/>
</Fragment>
我想做的是在我的父页面上呈现不同的组件,顺序很重要
假设'grid'
映射到组件
和'not-grid'
映射到
,那么我的父页面的最终结果应该是这样的:
"content": [
{
"type": "grid",
"value": {
"grid": [
{
"title": "Fast and reliable",
"subtitle": "Hello there testing this out man",
"button_page": 3,
"image": 2
}
]
},
"id": "e5e370e2-aef0-4ef8-b34f-c4bf9db16e22"
} ,
{
"type": "not-grid",
"value": {
"grid": [
{
"title": "Fast and reliable",
"subtitle": "Hello there testing that out man",
"button_page": 3,
"image": 2
}
]
},
"id": "e5e370e2-aef0-4ef8-b34f-c4bf9db16e12"
}
]
<Fragment>
<Grid/>
<NotGrid/>
</Fragment>
我不知道我该如何解决这个问题,以前有人做过类似的事情吗
我觉得应该有一个函数可以帮助我将正确的“类型”映射到相关的“组件”,但是我不确定如何在代码中实现这一点。您可以将类型分组并将其传递给组件
let内容=[
{
“类型”:“网格”,
“价值”:{
“网格”:[
{
“标题”:“快速可靠”,
“副标题”:“你好,正在测试这个人”,
“按钮页面”:3,
“图像”:2
}
]
},
“id”:“e5e370e2-aef0-4ef8-b34f-c4bf9db16e22”
},
{
“类型”:“非网格”,
“价值”:{
“网格”:[
{
“标题”:“快速可靠”,
“副标题”:“你好,测试那个男人”,
“按钮页面”:3,
“图像”:2
}
]
},
“id”:“e5e370e2-aef0-4ef8-b34f-c4bf9db16e12”
}
]
让grid=content.filter(c=>c.type==“grid”);
让notGrid=content.filter(c=>c.type==“notGrid”);
您可以简单地.map()
有条件地将其传入组件:
const{render}=ReactDOM,
rootNode=document.getElementById('root'))
常量网格=()=>我是网格
const NoGrid=()=>我不是网格
常量数据=[{type:'grid'},{type:'no grid'}]
常量应用=()=>{
返回(
data.map(({type})=>type=='grid'?:type=='no grid'?:null)
)
}
渲染(
,
根节点
)
使用map
方法应该很容易,这在React中非常常见。在没有看到您的组件或您尝试过的内容的情况下,很难给出更多细节。