我正在学习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>
答案 0 :(得分:2)
从我在这里看到的,返回的错误将是特定于请求的,而不是特定于评论的。在那个范例中,给每个注释一个错误属性是没有意义的。相反,在这种情况下,我会保留某种数组来存储错误:
this.setState({
errors: this.errors.push(err);
});
然后,您可以拥有自己创建的单独<ErrorDisplay/>
组件,该组件将错误数组作为prop。每当数组发生变化时,它可能会显示最近的错误几秒钟。它取决于你。
顺便说一句,尽快挖掘Flux。如果不是Flux,那么别的东西。 Facebook上的人们会热切地告诉你,要避免在React组件中保持这样的确定状态。在熟悉React时,这是一个必要的邪恶,所以不要担心。