Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React中返回错误消息_Javascript_Reactjs - Fatal编程技术网

Javascript 在React中返回错误消息

Javascript 在React中返回错误消息,javascript,reactjs,Javascript,Reactjs,我在学英语。我在看教程- 在提交脚本时,从服务器读取JSON: handleCommentSubmit: function(comment) { var comments = this.state.data; comments.push(comment); this.setState({data: comments}, function() { // `setState` accepts a callback. To avoid (improbable) ra

我在学英语。我在看教程-

在提交脚本时,从服务器读取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)
      });
    });
  },
并更新
数据
。如何从JSON发送错误消息?大概是这样的:

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

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

this.setState({
  errors: this.errors.push(err);
});
然后,您可以拥有自己创建的一个单独的
组件,该组件将错误数组作为道具接收。每当阵列发生更改时,它可能会在几秒钟内显示最近的错误。这取决于你


顺便说一下,请尽快深入研究。如果不是通量,那么还有别的东西。Facebook的人会急切地告诉你,在React组件中保留这样的确定状态是应该避免的。不过,在熟悉React时,这是一个必要的缺点,所以不要担心。

谢谢。“如果不是通量,那么还有别的东西”。你有什么建议吗?有些人也把棱角和反应结合起来。我的观点是,一旦在实际应用程序中使用React,请确保它只处理视图,并将数据/模型/控件/等留给其他代理。作为一部分,我强烈推荐Flux。Fluxible(来自Yahoo)和Reflech是Flux范例的两个优秀实现。在GitHub上查看它们。@NickBolsh使用react路由器进行路由。与视图相关的所有内容都是React组件,而状态和逻辑都是以流量方式处理的。这里有8个用于通信的无流量策略:其中一个可以使用的是所谓的观察者模式(publissubs),这就是我使用的。
this.setState({
  errors: this.errors.push(err);
});