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

Bom*_*ber 30 superagent reactjs

我试图使用用户代理将json设置为一个状态,我得到错误:

Uncaught Invariant Violation:对象无效作为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>
    );
}
Run Code Online (Sandbox Code Playgroud) 服务
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.');
                }
            });
    }
Run Code Online (Sandbox Code Playgroud) 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
},......
]}
Run Code Online (Sandbox Code Playgroud)

小智 18

你不能这样做:{this.state.arrayFromJson}因为你的错误暗示你要做的事情是无效的.您正在尝试将整个数组渲染为React子级.这是无效的.您应该遍历数组并渲染每个元素.我习惯.map这样做.

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

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

希望能帮助到你!


jay*_*bee 11

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