【问题标题】:React using JQuery post+get data使用 JQuery post+get 数据做出反应
【发布时间】:2017-07-21 07:02:13
【问题描述】:

我用它从 Django 服务器获取todos

getTodos(){
    $.ajax({url: "http://localhost:8000/todos/",
            success: function(data){
                this.setState({todos:data},function(){console.log(data)})}.bind(this),
            cache: false});
}

这是发布一个新的todo 并更新状态:

  handleAddTodo(title,text){
        $.post("http://localhost:8000/todos/",{title:title,text:text},this.getTodos());
    }

所以回调函数this.getTodos() 将从服务器获取新数据。但是好像服务端没有更新?

在图片中,第一个日志来自初始数据获取。最后一个来自回调函数。

【问题讨论】:

  • 您的查询是什么?
  • 我发完后,服务器端应该添加一个新的todo,然后get请求应该返回新的todo,但还是返回旧版本的todo,这是什么原因?

标签: javascript jquery django reactjs httprequest


【解决方案1】:

我认为这行有问题:

$.post("http://localhost:8000/todos/",{title:title,text:text},this.getTodos());

在这里,您需要传递一个函数,该函数将在 post 部分成功后触发,但您不是传递函数,而是通过使用 () 调用函数来传递函数返回的值。通过这种方式,此函数将与 post call 并行调用,检查网络部分您将同时看到两个调用。

要么使用arrow function

$.post("http://localhost:8000/todos/",
       {title:title,text:text}, 
       () => {
           this.getTodos()
       }
);

或者这样写:

$.post("http://localhost:8000/todos/",
       {title:title,text:text}, 
       this.getTodos
);

并在构造函数中绑定getTodos方法:

this.getTodos = this.getTodos.bind(this);

查看DOC了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2016-01-27
    • 2017-11-25
    • 1970-01-01
    • 2021-04-04
    相关资源
    最近更新 更多