首页 > 解决方案 > 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

标签: javascriptreactjs

解决方案


您可以简单地.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>


推荐阅读