Using for loops and switch cases in React to dynamically render different components

我是研究僧i 提交于 2019-12-02 17:59:19

You should return value from first .map, in your case it is result from inner .map

var elements = myPackage.map(function(myObj){
  return myObj.sectionInfo.map(function(myObj1) {
     // ...  
  });
});

Update:

Based on your new update, you can change your code like this

var App = React.createClass({

  section: function(myObj, parentIndex) {
    return myObj.sectionInfo.map(function(myObj1, index) {
      const key = parentIndex + '.' + index;

      switch(myObj1.elementType) {
        case 1:
          return <Component1 text = {myObj1.text} key={ key } />
        case 2:
          return <Component2 text = {myObj1.text} key={ key } />
      }
    });
  },

  render: function() {
    var elements = myPackage.map(function(myObj) {
      return <div>
        { this.section(myObj, index) }
      </div>
    }, this);

    return <div className="App">
     { elements }
    </div>;
  }
});

To do a switch case in JSX do it as follow:

   {{
    sectionA: (
      <SectionAComponent />
    ),
    sectionB: (
      <SectionBComponent />
    ),
    sectionC: (
      <SectionCComponent />
    ),
    default: (
      <SectionDefaultComponent />
    )
  }[section]}

for inline / not created new function ,you can use this way

<div>
    {(() => {
        switch (myObj1.elementType) {
            case 'pantulan':
                return <Component1 text = {myObj1.text} key={ key } />
            default :
                null
        }
    })()}
</div>

Recommended way by React: React Docs

const components = {
  photo: PhotoStory,
  video: VideoStory
};

function Story(props) {
  // Correct! JSX type can be a capitalized variable.
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;
}
ctrlplusb

You are missing a return as stated in the answer by Alexander T, but I would also recommend adding a key to each of your elements. React depends on this value for it's diff'ing algorithm, you could do something like:

render: function(){
  var elements = myPackage.map(function(myObj, pIndex){
    return myObj.sectionInfo.map(function(myObj1, sIndex){
      var key = pIndex + '.' + sIndex;            
      switch(myObj1.elementType) {
        case 1: return(
          <Component1 key={key} text={myObj1.text}/>
        );
        case 2: return(
          <Component2 key={key} text={myObj1.text}/>
        )
      }
    })
  });
  return(
    <div className="App">
      {elements}
    </div>
  )
}

Read here for more info: https://facebook.github.io/react/docs/multiple-components.html#dynamic-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!