在ajax调用之后反应组件状态更改,但不重新呈现组件

时间:2018-08-25 15:18:41

标签: javascript ajax reactjs

在这一部分,用户可以对帖子发表评论。在服务器端对其进行检查并接收到数据之后,我尝试更改this.state.comments值。这样就完成了。但是问题是,它没有更改组件的注释部分。 我已经阅读了有关重新渲染的先前问题,因此请不要将其标记为重复。下面是代码:

$.post("requests.php", {
    requestKey: 'newComment',
    commenterUser: commenterUser,
    commenterEmail: commenterEmail,
    theComment: theComment,
    pnum: pnum}, function(data, status, xhr){
      if(status == 'success'){
        if(data == 'commented'){
          this.setState({
            comments: data
          })
        }else{

        }
      }
    });

收到的data是与该帖子相关的所有评论,而“评论”部分是显示所有评论的地方。

3 个答案:

答案 0 :(得分:5)

您也可以使用箭头功能代替手动绑定。

this.setState不起作用,因为在使用常规功能时存在范围问题。

将其更改为箭头功能。检查以下代码

   $.post("requests.php", {
        requestKey: 'newComment',
        commenterUser: commenterUser,
        commenterEmail: commenterEmail,
        theComment: theComment,
            pnum: pnum}, (data, status, xhr) => {
                if(status == 'success'){
                    if(data == 'commented'){
                        this.setState({
                            comments: data
                        })
                    }else{

              }
           }
       });

编辑:

如果要避免示波器问题,可以使用箭头功能。使用箭头函数时,无需在构造函数中手动绑定函数

 submitComment = () => {

 }

如果您使用普通功能并在该功能内使用状态或道具,那么您需要手动将当前对象引用到如下所示的局部变量

 let that = this;
 that.setState({
     name: “update”
 });

对不起,如果有任何错字。我正在用手机接听

答案 1 :(得分:2)

let _this = this;
$.post("requests.php", {
  requestKey: 'newComment',
  commenterUser: commenterUser,
  commenterEmail: commenterEmail,
  theComment: theComment,
  pnum: pnum
}, function(data, status, xhr){
    if  (status == 'success'){
       if(data == 'commented'){
          _this.setState({ comments: data })
       } else{

       }
    }
});

我认为问题在于您的this的范围,在JavaScript this中始终处于词法上下文中。

答案 2 :(得分:2)

您遇到范围问题。

让我们考虑这个例子:

function foo() {
    this.bar = 'lorem';
    this.ipsum = function() {
        console.log(this.bar);
    };
}

如果您呼叫ipsum,它将记录undefined,因为那里的this是指ipsum function。让我们考虑这个例子:

function foo() {
    this.bar = 'lorem';
    var that = this;
    this.ipsum = function() {
        console.log(that.bar);
    };
}

在这种情况下,that存储外部this,因此如果调用'lorem',则将记录ipsum。我们来看一个箭头功能的例子:

function foo() {
    this.bar = 'lorem';
    this.ipsum = () => {
        console.log(this.bar);
    };
}

在这种情况下,如果您调用ipsum 'lorem'将被写入控制台。

您也可以为此使用bind

让我们使用箭头功能作为示例:

$.post("requests.php", {
    requestKey: 'newComment',
    commenterUser: commenterUser,
    commenterEmail: commenterEmail,
    theComment: theComment,
    pnum: pnum}, (data, status, xhr) => {
      if(status == 'success'){
        if(data == 'commented'){
          this.setState({
            comments: data
          })
        }else{

        }
      }
    });
相关问题