2015-04-09 12 views
35

Sto provando a ripetere tutte le chiavi in ​​un hash, ma non viene restituito alcun output dal ciclo. console.log() uscite come previsto. Qualche idea sul perché il JSX non viene restituito ed emesso correttamente?React JSX: Iterazione attraverso un hash e restituzione di elementi JSX per ogni chiave

var DynamicForm = React.createClass({ 
    getInitialState: function() { 
    var items = {}; 
    items[1] = { name: '', populate_at: '', same_as: '', 
       autocomplete_from: '', title: '' }; 
    items[2] = { name: '', populate_at: '', same_as: '', 
       autocomplete_from: '', title: '' }; 
    return { items }; 
    }, 



    render: function() { 
    return (
     <div> 
     // {this.state.items.map(function(object, i){ 
     //^This worked previously when items was an array. 
     { Object.keys(this.state.items).forEach(function (key) { 
      console.log('key: ', key); // Returns key: 1 and key: 2 
      return (
      <div> 
       <FieldName/> 
       <PopulateAtCheckboxes populate_at={data.populate_at} /> 
      </div> 
      ); 
     }, this)} 
     <button onClick={this.newFieldEntry}>Create a new field</button> 
     <button onClick={this.saveAndContinue}>Save and Continue</button> 
     </div> 
    ); 
    } 

risposta

72
Object.keys(this.state.items).forEach(function (key) { 

Array.prototype.forEach() non restituisce nulla - utilizzare .map() invece:

Object.keys(this.state.items).map(function (key) { 
    var item = this.state.items[key] 
    // ... 
+0

Sì, ho sostituito 'forEach' con' map' e ha funzionato. Grazie! :-) – martins

+1

var item = this.state.item [chiave]. non è come quello che hai pensato, devi usare var that = this, e that.state.item [chiave] – xiongjiabin

+0

'this' viene passato come secondo argomento, che imposta il valore appropriato di' this' quando la funzione è chiamato. –

1

un collegamento potrebbe essere:

Object.values(this.state.items).map({ 
    name, 
    populate_at, 
    same_as, 
    autocomplete_from, 
    title 
} => <div key={name}> 
     <FieldName/> 
     <PopulateAtCheckboxes populate_at={data.populate_at} /> 
    </div>);