2016-06-23 9 views
10

Sto cercando di impostare il JSON ad uno stato utilizzando user agent, ottengo l'errore:Promessa di errore: Gli oggetti non sono validi come Reagire bambino

Uncaught Violazione Invariant: Gli oggetti non sono validi come un bambino React (trovato: oggetto con le chiavi {...}). Se intendevi rendere una collezione di bambini, usa invece una matrice o avvolgi l'oggetto usando createFragment (oggetto) dai componenti aggiuntivi di React.

metodo per impostare lo stato:

getInitialState: function(){ 
    return { 
     arrayFromJson: [] 
    } 
}, 

loadAssessmentContacts: function() { 
    var callback = function(data) { 
     this.setState({arrayFromJson: data.schools}) 
    }.bind(this); 

    service.getSchools(callback); 
}, 

componentWillMount: function(){ 
    this.loadAssessmentContacts(); 
}, 

onTableUpdate: function(data){ 

    console.log(data); 

}, 

render: function() { 

    return (
     <span>{this.state.arrayFromJson}</span> 
    ); 
} 

servizio

getSchools : function (callback) { 
     var url = 'file.json'; 
     request 
      .get(url) 
      .set('Accept', 'application/json') 
      .end(function (err, res) { 
       if (res && res.ok) { 
        var data = res.body; 
        callback(data); 

       } else { 
        console.warn('Failed to load.'); 
       } 
      }); 
    } 

JSON

{ 
"schools": [ 
{ 
    "id": 4281, 
    "name": "t", 
    "dfe": "t", 
    "la": 227, 
    "telephone": "t", 
    "address": "t", 
    "address2": "t", 
    "address3": "t", 
    "postCode": "t", 
    "county": "t", 
    "ofsted": "t", 
    "students": 2, 
    "activeStudents": 2, 
    "inActiveStudents": 0, 
    "lastUpdatedInDays": 0, 
    "deInstalled": false, 
    "inLa": false, 
    "status": "unnassigned", 
    "authCode": "t", 
    "studentsActivity": 0 
},...... 
]} 

risposta

6

Non si può fare questo: {this.state.arrayFromJson} Come vostro errore suggerisce ciò che si sta cercando di fare non è valido. Stai cercando di rendere l'intero array come un bambino React. Questo non è valido Dovresti scorrere l'array e rendere ogni elemento. Io uso .map per farlo.

sto incollando un link da dove si può imparare come rendere gli elementi da un array con Reagire.

http://jasonjl.me/blog/2015/04/18/rendering-list-of-elements-in-react-with-jsx/

Speranza che aiuta!

4

Non si può semplicemente restituire un array di oggetti perché non c'è niente narrazione Reagire come rendere questo. Dovrai restituire un array di componenti o elementi come:

render: function() { 
    return (
    <span> 
     // This will go through all the elements in arrayFromJson and 
     // render each one as a <SomeComponent /> with data from the object 
     {this.state.arrayFromJson.map(function(object) { 
     return (
      <SomeComponent key={object.id} data={object} /> 
     ); 
     })} 
    </span> 
); 
} 
Problemi correlati