在reactjs中显示JSON数组数据

时间:2016-10-20 17:56:06

标签: reactjs

我可能犯了一个愚蠢的错误,但我有这个REST API输出,我通过React在UI中消耗,我部分得到输出。当我控制日志时,我得到输出(testRows是AJAX中的数据 - this.setState({testRows:data});):

this.state.testRows.Type as 'Application Performance'     

但是当我执行this.state.testRows.Names [0]打印第一个值,即desc2时,我面临一个错误。在反应中显示或打印JSON数组值的正确方法是什么?

{

"Names": [
"desc2",
"desc3"
],
"Result": 0,
"Type": "Application Performance",
"dateTime": [
"2016-07-26 20:35:55",
"2016-07-26 20:35:55"
 ]

}

ReactJS:

var App = React.createClass({

    getInitialState: function () {
        return {

            testRows: []

        };
    },

    componentWillMount: function (event) {

        $.ajax({
            type: "GET",
            crossDomain: true,
            url: /details/3,
            success: function(data) {
                this.setState({testRows: data});
            }.bind(this),
            error:function(data) {
                alert("Data sending failed");
            }
        });
    },

    render: function() {

        console.log(this.state.testRows.Type); ~~ I get the output 
        console.log(this.state.testRows.Names[0]); ~~ Error

        return (

        );
    }
});

var element = document.getElementById('content');
ReactDOM.render(React.createElement(App), element);

1 个答案:

答案 0 :(得分:1)

You are trying to console log the Names from your render method. Render method gets called immediately after the component is mounted, which means that your ajax has not completed by that time and so your state does not have Names and hence when you try to access an undefined error is thrown.

But after your ajax is completed and state is set, and when render is called again the if clause satisfies and your code works as the names is now available.