简体   繁体   English

React.js教程:注释不会添加到列表中

[英]React.js tutorial: comments don't append in the list

I am doing React.js tutorial and here is my code: 我正在做React.js教程,这是我的代码:

//Comment box
var CommentBox = React.createClass({
  loadCommentsFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
        console.log('Data has obtained... Refresh state')
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  handleCommentSubmit: function(comment) {
    var comments = this.state.data;
    var newComments = comments.concat([comment]);
    this.setState({data: newComments});
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: comment,
      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 onCommentSubmit={this.handleCommentSubmit} />
        </div>
    );
  }
});

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

//Comment form
var CommentForm = React.createClass({
  handleSubmit: function(e) {
    e.preventDefault();
    var author = React.findDOMNode(this.refs.author).value.trim();
    var text = React.findDOMNode(this.refs.text).value.trim();
    if (!text || !author) {
      return;
    }
    this.props.onCommentSubmit({author: author, text: text});
    //TODO: send request to the server
    React.findDOMNode(this.refs.author).value = '';
    React.findDOMNode(this.refs.text).value = '';
  },
  render: function() {
    return (
        <form className="commentForm" onSubmit={this.handleSubmit}>
          <input type="text" placeholder="Your name" ref="author" />
          <input type="text" placeholder="Say something..." ref="text" />
          <input type="submit" value="Post" />
        </form>
    );
  }
});

//Comment
var converter = new Showdown.converter();
var Comment = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="comment panel">
        <h3 className="commentAuthor">
          {this.props.author}
        </h3>
        <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
      </div>
    );
  }
});

React.render(
    <CommentBox url="comments.json" pollInterval={2000} />,
    document.getElementById('example')
);

HTML file looks like this: HTML文件如下所示:

<!DOCTYPE html>
<html>
<head>
  <title>8R</title>
  <meta charset="utf-8">
  <script src="react.js"></script>
  <script src="JSXTransformer.js"></script>
  <script src="jquery-2.1.3.min.js"></script>
  <script src="showdown.min.js"></script>
</head>
<body>

<div id="example"></div>

<script type="text/jsx" src="app.js"></script>
</body>
</html>

And i have comments.json file with comments: 而且我有带有评论的comments.json文件:

[
  {"author": "Pete Hunt", "text": "This is one comment"},
  {"author": "Jordan Walker", "text": "This is *another* comment"},
  {"author": "Mary Jane", "text": "My comment is the best comment"},
  {"author": "Peter Parker", "text": "Have you called spider-man?"}
]

Those comments appear in the list, but when i type my own comment in the comment form and submit it, it does not appear in the list. 这些评论出现在列表中,但是当我在评论表单中键入自己的评论并提交时,它不会出现在列表中。 In Chrome it just blinks for a part of a second and disappears and that's all. 在Chrome浏览器中,它只闪烁一秒钟,然后消失,仅此而已。 I have tried to do it on Webstorm's localhost and on MAMP server and i've gotten the same result. 我尝试在Webstorm的localhost和MAMP服务器上执行此操作,并且得到了相同的结果。 What is the problem? 问题是什么?

If anyone else gets here and wants to use their own PHP server which they've already setup (instead of using the react server scripts) you can do like this: 如果其他任何人到达这里并希望使用他们已经设置的自己的PHP服务器(而不是使用react服务器脚本),则可以执行以下操作:

// in your commentsBox class declaration
handleCommentSubmit: function(comment) {

   console.log(comment);
   //console.log(this.props.url);

   var comments = this.state.data;
   var newComments = comments.concat([comment]);

   this.setState({data: newComments});

   $.ajax({
        url: '../update_json_manager.php', // declare your own file to post to
        dataType: 'json',
        type: 'POST',
        data: comment,
        success: function(data) {
          this.setState({data: data});
          console.log(data);
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(xhr, status, err.toString());
        }.bind(this)
   });

},

Then you can receive the post and update your json file like this (in a file called update_json_manager.php in the same directory as comments.json : 然后,您可以接收该帖子并像这样更新您的json文件(在与comments.json相同的目录中的一个名为update_json_manager.php的文件中:

<?php
$comments = file_get_contents('comments.json');

$commentsDecoded = json_decode($comments, true);
$commentsDecoded[] = ['author'  => $_POST['author'],
                      'text'    => $_POST['text']];

$comments = json_encode($commentsDecoded, JSON_PRETTY_PRINT);
file_put_contents('comments.json', $comments);
?>

The zip you can download from Github for the React example you mention includes server scripts for a variety of languages, which will handle the JSON data update in the example. 您可以从Github下载用于您提到的React示例的zip文件,其中包含针对多种语言的服务器脚本,这些脚本将处理示例中的JSON数据更新。

So, if you download and use one of those server scripts to run the examples locally, you will see your code will work. 因此,如果下载并使用这些服务器脚本之一在本地运行示例,您将看到代码可以正常工作。 The ajax call will send your comment data to the url specified and the server script will take care of updating the JSON comments file. ajax调用会将您的注释数据发送到指定的url,服务器脚本将负责更新JSON注释文件。

HTH HTH

I think what you can do is to comment out the setInterval function in your componentDidMount. 我认为您可以做的是在componentDidMount中注释掉setInterval函数。

componentDidMount: function() {
    this.loadCommentsFromServer();
    //setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},

If you check your comments.json, you will find your comments are not appended there. 如果您检查comments.json,则会发现您的评论未附加在此处。 So every time you fetch, your list will go back to original state. 因此,每次获取时,您的列表都会返回到原始状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM