【问题标题】:Ajax post call cannot access 'this' inside .thenAjax post call 无法访问 .then 内部的“this”
【发布时间】:2020-12-16 20:20:35
【问题描述】:

我知道问题在于“this”在技术上超出了函数的范围(该函数在反应类中定义),但我尝试了几种不同的方式绑定它,但我似乎无法想办法。

const sendEmail = () => {
  this.openBackDrop();
  var data = {
    service_id: "redacted",
    template_id: "redacted",
    user_id: "redeacted",
    template_params: {
      from_name: this.state.name,
      message: this.state.message,
      rating: this.state.rating,
      requested: this.state.requestedProjects.toString(),
    },
  };
  $.ajax("url_goes_here", {
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
  })
    .done(function () {
      alert("Your mail is sent!");
      this.setState({
        requestedProjects: [],
        rating: "0",
        name: "",
        email: "",
        message: "",
        buttonDisabled: true,
        emailDisabled: true,
        backDrop: false,
      });
    })
    .fail(function (error) {
      alert("Oops... " + JSON.stringify(error));
    });
};

谁能给我一个快速的骨头在这里?需要明确的是,我希望状态发生不同的事情,具体取决于请求是否成功,否则我只会在函数的主块中执行。

【问题讨论】:

    标签: reactjs ajax state


    【解决方案1】:

    你的代码中没有then,所以我猜你的意思是done。最简单的方法是使用箭头表达式,而不是function(){...} 这样做() => {...} 这种方式与sendEmail 内部相同。您还可以创建函数并将其存储在成本中,即const onDone = function(){...},然后将其绑定到this,例如.done(onDone.bind(this))

    【讨论】:

      猜你喜欢
      • 2012-06-17
      • 2017-11-26
      • 2019-04-07
      • 2015-05-25
      • 2015-09-25
      • 2015-12-09
      • 1970-01-01
      • 2011-02-13
      • 2019-04-06
      相关资源
      最近更新 更多