recorrer react loop iterating for component array loops reactjs switch-statement react-jsx

loops - loop - react iterating



Uso de bucles y casos de conmutación en React para renderizar dinámicamente diferentes componentes (5)

Estoy tratando de hacer que los componentes condicionen el uso de conmutadores en React JSX. Estoy tratando de construir algo que se lea de una estructura json específica y genere los datos. Dado que puede haber muchos componentes y datos diferentes, estoy intentando renderizarlos dinámicamente. Vea mi código a continuación, no recibo ningún error pero los componentes no se procesan. Dentro de mi html, solo puedo ver. Esto significa que el bucle no está funcionando. Intenté usar el mismo bucle en JS de vainilla y funciona.

var myPackage = [{ sectionInfo:[{ elementType: 1, text: "This is text from element type 1" }] }, { sectionInfo:[{ elementType: 2, text: "This is text from element type 2" }] }]; var App = React.createClass({ render: function(){ var elements = []; elements = myPackage.map(function(myObj){ myObj.sectionInfo.map(function(myObj1){ switch(myObj1.elementType){ case 1: return( <Component1 text = {myObj1.text}/> ); break; case 2: return( <Component2 text = {myObj1.text}/> ) break; } }) }); return( <div className="App"> {elements} </div> ) } }); var Component1 = React.createClass({ render:function(){ return( <div className = "element1"> {this.props.text} </div> ) } }); var Component2 = React.createClass({ render:function(){ return( <div className = "element2"> {this.props.text} </div> ) } }); ReactDOM.render(<App/>,document.getElementById(''container''));

Edición: hice algunas adiciones al código, y ahora estoy enfrentando un nuevo problema. Aquí está el nuevo código:

var App = React.createClass({ render: function(){ var elements = []; elements = myPackage.map(function(myObj){ return( <div> myObj.sectionInfo.map(function(myObj1){ switch(myObj1.elementType){ case 1: return( <Component1 text = {myObj1.text}/> ); break; case 2: return( <Component2 text = {myObj1.text}/> ) break; } } </div> ) }); return( <div className="App"> {elements} </div> ) } });

Quiero hacer cada vez dentro de un div. De modo que si una sección tiene más de 3 elementos, entonces las 3 deben estar dentro de un div.


Debe devolver el valor desde el primer .map , en su caso, es el resultado de un .map interno.

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

Actualizar:

Según tu nueva actualización, puedes cambiar tu código de esta manera

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>; } });


Le falta una devolución, tal como se indica en la respuesta de Alexander T , pero también recomendaría agregar una clave a cada uno de sus elementos. React depende de este valor para su algoritmo de diferencia, podría hacer algo como:

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> ) }

Lea aquí para obtener más información: https://facebook.github.io/react/docs/multiple-components.html#dynamic-children


Manera recomendada por 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} />; }


Para hacer un cambio de caso en JSX hazlo como sigue:

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


Para la nueva función inline / no creada, puede usar esta forma

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