ReactJS教程停留在url属性

时间:2015-05-04 23:19:35

标签: reactjs

我当前的index.html并且停留在externalise json文件中:

<html>
  <head>
    <title>Hello React</title>
    <script src="https://fb.me/react-0.13.2.js"></script>
    <script src="https://fb.me/JSXTransformer-0.13.2.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
  </head>
  <body>
    <div id="content"></div>
    <script type="text/jsx">
      var Comment = React.createClass({
        render: function(){
          return (
            <div className="comment">
              <h2 className="commentAuthor">
                {this.props.author}
              </h2>
              <span dangerouslySetInnerHTML={{__html:marked(this.props.children.toString(), {sanitize:true})}} />
            </div>
          );
        }
      });

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

      var CommentForm = React.createClass({
        render: function(){
          return (
            <div className="commentForm">
              Hello, world! I am a CommentForm
            </div>
          );
        }
      });
      var CommentBox = React.createClass({
        render: function(){
          return (
            <div className="commentBox">
              <h1>Comments</h1>
              <CommentList data={this.props.data} />
              <CommentForm />
            </div>
          );
        }
      });
      React.render(
        <CommentBox url="comments.json" />,
        document.getElementById('content')
      );
    </script>
  </body>
</html>

comments.json文件

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

控制台抱怨this.props.data未定义,查看服务器访问日志,它未加载comments.json文件

1 个答案:

答案 0 :(得分:2)

您缺少加载评论的代码。如果您在教程中向下滚动一下,您将看到可以将此代码添加到注释框组件中:

var CommentBox = React.createClass({
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: 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)
    });
  },
  render: function() {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList data={this.state.data} />
        <CommentForm />
      </div>
    );
  }
});