简体   繁体   English

无法理解React JS教程中的提交表单

[英]can't understand submit form in React JS tutorial

Here is the submit function for react JS tutorial here I can't understand the success function, because data is supposed to be an array. 这是react JS教程的Submit函数, 在这里我无法理解成功函数,因为数据应该是数组。 Yet on success, its overriding the array with a singular comment. 然而,如果成功了,它会以一个唯一的注释覆盖整个数组。

I'm using this code and overriding this array with one comment means the map function doesn't work, and it breaks it all. 我正在使用此代码,并用一个注释覆盖此数组,这意味着map函数不起作用,并且将其全部破坏了。

Why is seemingly incorrect code in the tutorial and how do I fix it? 为什么本教程中的代码看似不正确,我该如何解决?

also, what is a better function than Date.now() for the comment id? 此外,还有什么比Date.now()更好的评论ID功能呢?

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)
    });
  },

Even though I thought it was a client side problem, I fixed it by changing the response from my server to be an array. 即使我认为这是客户端问题,我还是通过将服务器的响应更改为数组来解决此问题。

I won't mark this answer as accepted though as I believe there could be a client side way of solving this? 我不会将此答案标记为已接受,因为我相信可能会有解决此问题的客户端方法?

using DRF, and a custom viewset, I had to change the create view to return the same as the list view 使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM