ReactJS - 从json文件加载数据时出错

时间:2015-06-10 06:08:44

标签: json reactjs

    <html>
    <head>
    <meta charset="utf-8">
    <title>React component</title>
    <script src="build/react.js"></script>
    <script src="build/JSXTransformer.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    </head>
    <body>
    <div id="myContent"></div>
    <script type="text/jsx">
    var ChatMessagesLists = React.createClass({
    getInitialState: function() {
        return {data: {chat_messages:[]}};
    },
    render: function(){
        return
            (
                <div className="chatLstsWrapper">
                <h1>Chat Messages</h1>
                <ChatMessagesData data={this.state.data} />
                </div>
            )
    },
    componentDidMount: function(){
        $.ajax({
            url: 'jsontextfile.json',
            dataType: 'json',
            success: function(data){
                     this.setState({data: {chat_messages:[]}});
                }
            });
    }
    });

    var ChatMessagesData = React.createClass({
    render:function(){
        console.log(this.props.data.chat_messages);
        return(
            <ul className="chatLsts">
                {
                    this.props.data.chat_messages.map(function(chatmessages){
                        return <li>{chatmessages.from_account_id}</li>
                    })
                }
                </ul>
        )
    }
    })

    React.render(<ChatMessagesLists />,document.getElementById("myContent"));

    </script>
    </body>
    </html>


JSON File
{
    "message": "List of chat messages",
    "data": {
        "since_index": 1,
        "before_index": 2,
        "chat_messages": [
            {
                "text": "Load more",
                "type": "text",
                "key": "8ff134e7-e302-445b-903e-0038097c8a29"
            },
            {
                "text": "my test data",
                "type": "text",
                "key": "3c7c3065-3701-4350-a64a-8a52f9fe1578"
            },
            {
                "text": "My message",
                "type": "text",
                "key": "40f7c342-a019-44c3-ad2b-8b2ae018972b"
            }
        ],
    "max_results": 20
    },
}

加载数据时低于错误。任何人都可以建议我错在哪里

错误:不变违规:ChatMessagesLists.render():必须返回有效的ReactComponent。您可能已经返回了undefined,数组或其他一些无效对象。

1 个答案:

答案 0 :(得分:0)

HY,

你试过了吗?

 var ChatMessagesData = React.createClass({
    render:function(){
     var items = this.props.data.chat_messages.map(function(chatmessages){
       return <li>{chatmessages.from_account_id}</li>;
      })
    return(
        <ul className="chatLsts">
            {
              items  
            }
        </ul>
    );
});

PS:在Ajax回调中,你不能更新状态:

success: function(data){
    this.setState({data: {chat_messages: data}});
}