如何在React中获取json数据

时间:2016-08-23 21:05:27

标签: javascript jquery json reactjs

我是新手,我在官方网站上学习辅导。 所以,我的应用程序中有结构:

-js
  -notes.js
  -comment.json
index.html

notes.js有下一个代码:

var CommentBox = React.createClass({
    loadCommentsFromServer: function() {
        $.ajax({
            url: this.props.url,
            dataType: 'json',
            cache: false,
            success: function(data) {
                this.setState({data: 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.loadCommentsFromServer();
        setInterval(this.loadCommentsFromServer, this.props.pollInterval);
    },
    render: function(){
        return (
            <div className="commentBox">
                <h1>Comments</h1>
                <CommentList data={this.state.data} />
                <CommentForm />
            </div>
        );
    }
});

var CommentList = React.createClass({
    render: function(){
        var commentNodes = this.props.data.map(function (comment) {
            return (
                <Comment author={comment.author} key={comment.id}>
                    {comment.text}
                </Comment>
            );
        });
        return (
            <div className="commentList">
                {commentNodes}
            </div>
        );
    }
});

var CommentForm = React.createClass({
    render: function () {
        return (
            <div className="commentForm">
                Hello, world! I am a CommentForm.
            </div>
        );
    }
});

var Comment = React.createClass({
    render: function () {
        return (
            <div className="comment">
                <h2 className="commentAuthor">
                    {this.props.author}
                </h2>
                <p>
                    {this.props.children}
                </p>
            </div>
        );
    }
});


ReactDOM.render(
    <CommentBox url="comment.json" pollInterval={2000} />,
    document.getElementById('content')
);

这里是我的文件数据&#34; comment.json&#34;:

[
  {"id": "1", "author": "Pete Hunt", "text": "This is one comment"},
  {"id": "2", "author": "Jordan Walke", "text": "This is *another* comment"}
]

但它不起作用,在控制台我有下一条消息:

jquery.js:9392 GET http://helper.com/views/com.json?_=1471986105038 404 (Not Found)

另一个:

notes.js:22 com.json error Not Found

也许我写了错误的url parametr:

   <CommentBox url="comment.json" pollInterval={2000} />

有人能帮助我吗?

0 个答案:

没有答案