ReactJS - 错误:对象作为React子对象无效

时间:2017-09-26 10:55:48

标签: javascript reactjs components

我试图了解访问和显示检索到的JSON对象的部分内容时出错了。我将返回的对象存储在一个数组中,用于返回的每个记录,并知道如何遍历JSON以访问JS中的正确属性/值,但是,我在我的ReactJS组件中努力做同样的事情。我对React仍然相对较新,似乎无法找到正确的遍历和显示JSON属性和数组的方法。通过我当前的设置,我得到Error: Objects are not valid as a React child (found: object with keys {recordDateSlugEdit, ... If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.任何帮助将不胜感激。

返回JSON Blob:

[
  {
    "recordDateSlugEdit": "2017-08-17",
    "recordId": 119,
    "title": "POS Core Campaign CPL Rose 40%",
    "created_at": "2017-09-01T11:57:28.561Z",
    "updated_at": "2017-09-01T11:57:45.798Z",
    "user_id": 237,
    "category_id": 81,
    "app_user": {
      "userIdHash": "",
      "fullNameSlug": "Steve Matthews",
      "firstName": "Steve",
      "lastName": "Matthews"
    },
    "category": {
      "categoryIdHash": "",
      "categoryName": "Organic"
    },
    "record_comments": [
      {
        "createdAtDateSlug": "9\/1\/2017 8:13 AM",
        "commentId": 11,
        "comment": "Donec sem sapien, scelerisque fermentum interdum at, imperdiet vel dolor. Pellentesque fringilla elit eget risus maximus, aliquet luctus odio luctus. Sed pretium",
        "recordId": 119,
        "userId": 236,
        "created_at": "2017-09-01T12:13:23.557Z",
        "updated_at": "2017-09-01T12:13:23.557Z",
        "record_id": 119,
        "user_id": 236,
        "app_user": {
          "userIdHash": "oqX1p3EO5b",
          "fullNameSlug": "Brad Feld",
          "userId": 236,
          "firstName": "Brad",
          "lastName": "Feld",
        }
      }
    ]
  },
  {
    "recordDateSlugEdit": "2017-08-08",
    "recordId": 118,
    "title": "Added New CTA to Pricing Page",
    "user_id": 236,
    "category_id": 82,
    "app_user": {
      "userIdHash": "",
      "fullNameSlug": "Brad Feld",
      "firstName": "Brad",
      "lastName": "Feld",
    },
    "category": {
      "categoryIdHash": "",
      "categoryName": "Website"
    },
    "record_comments": [

    ]
  }
]

我希望访问位于每个JSON记录中的record_comments数组中的对象上找到的属性。

以下是我的组件设置:

import React from 'react';
import fetch from 'node-fetch';


//Comment Form
class CommentForm extends React.Component{
    render() {
        return (
            <form action="/app/record/comment" method="post">
            </form>
        )
    }
};

//Comments List
class Comments extends React.Component{

    constructor(props, context) {
        super(props, context);
        this.state = this.context.data || window.__INITIAL_STATE__ || {records: []};
    }

    fetchList() {
        fetch('http://localhost:3000/api/test')
            .then(res => {
                return res.json();
            })  
            .then(data => {
                let records = data.map((record) => {
                    return(
                        <div key={record.record_comments.commentId}>
                            <li>{record.record_comments.comment}</li>
                        </div>
                    )
                })
                this.setState({ records: data });
            })  
            .catch(err => {
                console.log(err);
            });
    }

    componentDidMount() {
        this.fetchList();
    }

    render() {
        return (
            <div>
            <h2>Comments List</h2>
            <ul>
                {this.state.records}
            </ul>
            </div>
        )
    }
};

//Comment Container
export default class CommentBox extends React.Component {

    render() {
        return (
            <div className="record-comment-form">
                <h1>Sweet it Worked</h1>
                <CommentForm />
                <hr />
                <Comments />
            </div>
        );
    }
}

2 个答案:

答案 0 :(得分:0)

可能是<ul>的孩子的唯一元素是<li>。在您的情况下,您使用的是div。 你还需要改变
setState({records:data})setState({records})setState({records:records})

fetchList() {
    fetch('http://localhost:3000/api/test')
        .then(res => {
            return res.json();
        })  
        .then(data => {
            let records = data.map((record) => {
                return(

                        <li key={record.record_comments.commentId}>{record.record_comments.comment}</li>

                )
            })
            this.setState({ records:records});

        })  
        .catch(err => {
            console.log(err);
        });
}

答案 1 :(得分:0)

似乎在

this.setState({ records: data });

data - 不是有效的dom元素。 尝试用

替换它
this.setState({ records });

因为记录 - 似乎是一个jsx元素数组。