javascript - Rendering different child components based on data recieved , in a specific order
问题描述
I am currently using wagtail v2 API
to generate a dynamic page content for my react front end. The data comes like this :
"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"
}
]
What i wish to do is to render different component onto my parent page in which order matters .
So lets say 'grid'
maps to the component <Grid/>
and 'not-grid'
maps to <NotGrid/>
, then the end result of my parent page should look something like this :
<Fragment>
<Grid/>
<NotGrid/>
</Fragment>
Im not sure on how i should attempt to tackle the problem has anybody attempted to do something similar before?
I feel like there should be a function that helps me to map the correct 'type' to the associated 'component' , however im not sure how to implement this in code
解决方案
您可以简单地.map()
将它有条件地传入组件:
const { render } = ReactDOM,
rootNode = document.getElementById('root')
const Grid = () => <div>I'm grid</div>
const NoGrid = () => <div>I ain't no grid</div>
const data = [{type: 'grid'}, {type: 'no-grid'}]
const App = () => {
return (
data.map(({type}) => type == 'grid' ? <Grid /> : type == 'no-grid' ? <NoGrid /> : null)
)
}
render (
<App />,
rootNode
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
推荐阅读
- amazon-web-services - 找不到 AWS 身份池的规则设置
- javascript - 如果宽度溢出,如何使reactjs将图例重新绘制到下一行?
- windows - 禁用 Windows Server 2016 的自动 Windows 更新,使用 powershell 更改注册表项
- c - gst_init (&argc, &argv) 与 gst_value_table 崩溃为 nullptr
- mysql - 查询 mysql 以获取 2 个表,其中包含每月已售商品的摘要,包括未售出的商品
- python - 无法在python中导入文件
- python - 在 Python 中添加缺失的句点
- neo4j - Neo4j:使用 Cypher 创建具有唯一节点的图
- python - 我在从 Python 中的另一个文件导入列表时遇到困难
- vue.js - 无法读取 vuex 中 Store._callee 处未定义的属性“getProduct”(操作名称)