【问题标题】:Promise Error: Objects are not valid as a React childPromise 错误:对象作为 React 子对象无效
【发布时间】:2016-10-26 03:47:42
【问题描述】:

我正在尝试使用用户代理将 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>
    );
}
服务
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
},......
]}

【问题讨论】:

    标签: reactjs superagent


    【解决方案1】:

    你不能这样做:{this.state.arrayFromJson} 因为你的错误表明你试图做的事情是无效的。您正在尝试将整个数组呈现为 React 子级。这是无效的。您应该遍历数组并渲染每个元素。我使用.map 来做到这一点。

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

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

    希望对你有帮助!

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多