承诺错误:对象作为React子项无效

时间:2016-06-23 17:11:55

标签: reactjs superagent

我正在尝试使用用户代理将json设置为某个状态,我收到错误:

  

未捕获的不变违规:对象无效作为React子对象(找到:具有键{...}的对象)。如果您要渲染子集合,请使用数组,或者使用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
},......
]}

2 个答案:

答案 0 :(得分:16)

您无法执行此操作:{this.state.arrayFromJson}因为您的错误提示您尝试执行的操作无效。您正在尝试将整个数组渲染为React子级。这是无效的。您应该遍历数组并渲染每个元素。我使用.map来做到这一点。

我正在粘贴一个链接,您可以从中学习如何使用React从数组中渲染元素。

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

希望它有所帮助!

答案 1 :(得分:8)

你不能只返回一个对象数组,因为没有什么可以告诉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>
  );
}