2016-06-23 48 views
10

我想使用的用戶代理設置JSON來的狀態,我得到的錯誤:無極錯誤:對象是不是有效的做出反應的孩子

未捕獲不變違規:對象是不是一個陣營的孩子有效(找到:具有鍵{...}的對象)。如果您打算渲染一組兒童,請改用數組,或者使用React附加組件中的createFragment(object)來包裝對象。

方法來設置狀態:

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

服務

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 
},...... 
]} 

回答

6

你不能做到這一點:{this.state.arrayFromJson}由於你的錯誤建議你嘗試做是無效的。您試圖將整個數組渲染爲React子元素。這是無效的。您應該遍歷數組並呈現每個元素。我用.map來做到這一點。

我正在粘貼一個鏈接,您可以從中瞭解如何使用React渲染陣列中的元素。

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

希望它有幫助!

4

你不能只返回一個對象數組,因爲沒有什麼東西告訴React如何渲染它。您需要返回一組組件或元素,例如:

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> 
); 
} 
相關問題