React Tutorial - 添加评论后的页面刷新

时间:2016-07-27 10:39:44

标签: ajax reactjs

我正在通过官方的React教程并遇到一些麻烦。当我添加评论时,我希望评论会出现在视图中,并且会暂时显示,但页面会刷新,评论也会消失。

在一个相关的问题上(实际上只是一个小的FYI的请求,因为我还在学习AJAX),代码应该将注释添加到JSON。我假设这对Plunker不起作用,但是如果页面是实时的话,那里有足够的代码来实际更新JSON吗?

感谢您的帮助! Plunker链接和代码如下:

https://plnkr.co/edit/p76jB1W4Pizo0rDFYIwq?p=preview

    <script type="text/babel">
  // To get started with this tutorial running your own code, simply remove
  // the script tag loading scripts/example.js and start writing code here.
  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)
      });
    },
    handleCommentSubmit: function(comment) {
      var comments = this.state.data;
      // Optimistically set an id on the new comment. It will be replaced by an
      // id generated by the server. In a production application you would likely
      // not use Date.now() for this and would have a more robust system in place.
      comment.id = Date.now();
      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) {
          this.setState({data: comments});
          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>
      );
    }
  });

  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({
    getInitialState: function() {
      return {author: '', text: ''};
    },
    handleAuthorChange: function(e) {
      this.setState({author: e.target.value});
    },
    handleTextChange: function(e) {
      this.setState({text: e.target.value});
    },
    handleSubmit: function(e) {
      e.preventDefault();
      var author = this.state.author.trim();
      var text = this.state.text.trim();
      if (!text || !author) {
        return;
      }
      this.props.onCommentSubmit({author: author, text: text});
      this.setState({author: '', text: ''});
    },
    render: function() {
      return (
        <form className="commentForm" onSubmit={this.handleSubmit}>
          <input
            type="text"
            placeholder="Your name"
            value={this.state.author}
            onChange={this.handleAuthorChange}
          />
          <input
            type="text"
            placeholder="Say something..."
            value={this.state.text}
            onChange={this.handleTextChange}
          />
          <input type="submit" value="Post" />
        </form>
      );
    }
  });

  var Comment = React.createClass({
    rawMarkup: function() {
      var md = new Remarkable();
      var rawMarkup = md.render(this.props.children.toString());
      return { __html: rawMarkup };
    },

    render: function() {
      return (
        <div className="comment">
          <h2 className="commentAuthor">
            {this.props.author}
          </h2>
          <span dangerouslySetInnerHTML={this.rawMarkup()} />
        </div>
      );
    }
  });

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

</script>

1 个答案:

答案 0 :(得分:1)

正如您所说,您的问题是json文件中的信息是静态的(请参阅最后一段),因此每次刷新注释时,您都会丢失新注释。你可以处理它的方法是在第一次加载时使用json文件然后只是阻止刷新它们,只是将新的文件添加到注释框状态(毕竟这只是一个例子,你只是想看一些眼睛糖果,不是吗?)。

检查浏览器的控制台,您可以看到存储新文件的AJAX请求失败,您无法在Plunker上更新它,该文件是不可变的。