如何使用ReactJS访问嵌套的JSON?

时间:2016-04-17 08:17:20

标签: json reactjs

所以我有一个Drupal后端提供的这个JSON,我试图访问其中的不同字段。我不知道我做错了什么,因为控制台没有输出任何错误,但我仍然无法在fornt-end或任何其他字段中获得标题。

var Magazine = React.createClass({
    loadMagazinesFromServer: function() {
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        cache: true,
        success: function(data) {
          this.setState({data: data});
          console.log(data);
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    },
    getInitialState: function() {
      return {data: []};
    },


    componentDidMount: function() {
      this.loadMagazinesFromServer();
    },

    render: function () {
      return (
        <div> Magazine title: {this.state.data.title} </div>
      );
    }
});

ReactDOM.render( <Magazine  url='http://landliebe.lo/all-magazines/hal_json' /> , document.getElementById('content') );

这是我得到的JSON。

[
    {
        "nid": [
            {
                "value": "2"
            }
        ],
        "title": [
            {
                "value": "Praesent venenatis metus"
            }
        ],
        "uid": [
            {
                "target_id": "1",
                "url": "/user/1"
            }
        ],
        "body": [
            {
                "value": "<p>Morbi mattis ullamcorper velit.. Donec interdum, metus et hendrerit aliquet, dolor diam sagittis ligula, eget egestas libero turpis vel mi. Praesent ut ligula non mi varius sagittis. Etiam ultricies nisi vel augue.</p>\r\n\r\n<p>Praesent turpis. Sed cursus turpis vitae tortor. Vestibulum facilisis, purus nec pulvinar iaculis, ligula mi congue nunc, vitae euismod ligula urna in dolor. Nullam tincidunt adipiscing enim. Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum.</p>\r\n\r\n<p>Vivamus in erat ut urna cursus vestibulum. Maecenas nec odio et ante tincidunt tempus. Vivamus consectetuer hendrerit lacus. Mauris turpis nunc, blandit et, volutpat molestie, porta ut, ligula. Nulla sit amet est.</p>\r\n",
                "format": "basic_html",
                "summary": ""
            }
        ],
        "field_image": [
            {
                "target_id": "3",
                "alt": "",
                "title": "",
                "width": "2211",
                "height": "1382",
                "url": "http://landliebe.lo/sites/default/files/magazines/covers/London.jpg"
            }
        ],
    },
    {
        "nid": [
            {
                "value": "1"
            }
        ],
        "title": [
            {
                "value": "Phasellus accumsan"
            }
        ],
        "uid": [
            {
                "target_id": "1",
                "url": "/user/1"
            }
        ],
        "body": [
            {
                "value": "<p>Phasellus volutpat, metus eget egestas mollis, lacus lacus blandit dui, id egestas quam mauris ut lacus. Sed libero. Cras varius. Vivamus laoreet. Cras varius.</p>\r\n\r\n<p>Aenean posuere, tortor sed cursus feugiat, nunc augue blandit nunc, eu sollicitudin urna dolor sagittis lacus. Sed magna purus, fermentum eu, tincidunt eu, varius ut, felis. Praesent adipiscing. Proin viverra, ligula sit amet ultrices semper, ligula arcu tristique sapien, a accumsan nisi mauris ac eros. Pellentesque auctor neque nec urna.</p>\r\n\r\n<p>Fusce vulputate eleifend sapien. Nulla sit amet est. Curabitur turpis. Morbi mattis ullamcorper velit. Sed aliquam ultrices mauris.</p>\r\n",
                "format": "basic_html",
                "summary": ""
            }
        ],
        "field_image": [
            {
                "target_id": "2",
                "alt": "",
                "title": "",
                "width": "2457",
                "height": "1382",
                "url": "http://landliebe.lo/sites/default/files/magazines/covers/Facet%201.jpg"
            }
        ],
    }
]

有人可以帮助我:(?

2 个答案:

答案 0 :(得分:0)

下载chrome的反应工具,然后您就可以检查传递给组件的道具了。 https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en

我在这里猜测,因为我在你的例子中看不到你的反应组件,但你可能会将title属性作为数组传递。

答案 1 :(得分:0)

您正试图从title获取data,但您的数据是一个数组且没有title属性。我想,你需要显示杂志列表,你可以这样做:

var MagazineList = React.createClass({
    loadMagazinesFromServer: function() {
        $.ajax({
            url: this.props.url,
            dataType: 'json',
            cache: true,
            success: function(data) {
                this.setState({data: data});
                console.log(data);
            }.bind(this),
            error: function(xhr, status, err) {
                console.error(this.props.url, status, err.toString());
            }.bind(this)
        });
    },
    getInitialState: function() {
        return {data: []};
    },

    componentDidMount: function() {
        this.loadMagazinesFromServer();
    },

    render: function () {
        return (
            <div>
               {
                   // map all array element to React elements
                   this.state.data.map(magazine => (
                       <Magazine {...magazine} />
                   ))
               }
            </div>
        );
    }
});

var Magazine = React.createClass({
    render: function () {
        return (
            <div> Magazine title: {this.props.title} </div>
        );
    }
});

ReactDOM.render( <MagazineList url='http://landliebe.lo/all-magazines/hal_json' /> , document.getElementById('content') );