这是react JS教程here的提交函数 我无法理解成功函数,因为数据应该是一个数组。然而,在成功的情况下,它以一个单一的评论来压倒阵列。
我正在使用此代码并使用一个注释覆盖此数组意味着map函数不起作用,并且它会破坏所有这些。
为什么教程中看似错误的代码以及如何解决?
另外,对于评论ID,什么是比Date.now()更好的功能?
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)
});
},
答案 0 :(得分:0)
即使我认为这是客户端问题,我通过将服务器的响应更改为数组来修复它。
我不会将此答案标记为已被接受,但我相信可能有客户方式解决此问题?
使用DRF和自定义视图集,我不得不更改创建视图以返回与列表视图相同的内容
def create(self, request, *args, **kwargs):
object_serializer = self.get_serializer(data=request.data)
object_serializer.is_valid(raise_exception=True)
object_serializer.save()
headers = self.get_success_headers(object_serializer.data)
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)