Return React 中的错误信息

Return error message in React

我正在学习 ReactJS。我在看教程 - http://facebook.github.io/react/docs/tutorial.html

提交脚本时从服务器读取 JSON:

handleCommentSubmit: function(comment) {
    var comments = this.state.data;
    comments.push(comment);
    this.setState({data: comments}, function() {
      // `setState` accepts a callback. To avoid (improbable) race condition,
      // `we'll send the ajax request right after we optimistically set the new
      // `state.
      $.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)
      });
    });
  },

并更新 data。如何从 JSON 发送错误消息?像这样:

<Comment author={comment.author} key={index}>
    {comment.text}
    <div class="error">Error</div>
</Comment>

我应该在data中设置它吗: this.setState({[{name: 'John', text: 'text', error: 'error'}]});

并更改评论?:

<Comment author={comment.author} key={index}>
    {comment.text}
    <div class="error">{comment.error}</div>
</Comment>

从我在这里看到的情况来看,返回的错误是特定于请求的,而不是特定于评论的。在那个范例中,给每个评论一个错误 属性 是没有意义的。相反,在这种情况下,我会保留某种数组来存储错误:

this.setState({
  errors: this.errors.push(err);
});

然后你可以有一个你自己创建的单独的 <ErrorDisplay/> 组件,它接收错误数组作为 prop。每当数组发生变化时,也许它可以显示几秒钟的最新错误。由你决定。

顺便说一句,尽快深入Flux。如果不是 Flux,那就是其他东西。 Facebook 的人会急切地告诉你,在 React 组件中保持这样的确定状态是应该避免的。不过,这是熟悉 React 的必要之恶,所以不用担心。