反应在承诺中失去了"这个"背景

use*_*120 3 javascript ecmascript-6 reactjs es6-promise axios

我反应很新,可能犯了一个愚蠢的错误.我正在尝试使用能够返回承诺的axios进行api调用.当这个promise解析时,我想将结果传递给一个通过回调更新父级状态的函数.然而,看起来"这个"已经消失,因为我未定义.我想,随着它在未来的解决,不再是"这个"背景?我可以通过将回调分配给temp并使用它来绕过它,但它感觉很笨拙.这是代码:

axios.get(url)
  .then(function(response) {
    this.props.handler(response.data.thing)
  })
  .catch(function(error) {
    console.log(error)
  })
Run Code Online (Sandbox Code Playgroud)

这工作:

let handler = this.props.handler
axios.get(url)
  .then(function(response) {
    handler(response.data.word)
  })
  .catch(function(error) {
    console.log(error)
  })
Run Code Online (Sandbox Code Playgroud)

Cha*_*ish 9

这是箭头函数的用武之地.Arrow函数基本上this从上面维护,不要在函数内覆盖它.您可以在MDN上阅读更多内容.请记住,它是一个较新的功能,因此一些旧版浏览器不支持它.

以下代码是基于您的问题中的代码使用箭头函数的示例.

axios.get(url)
  .then((response) => {
    this.props.handler(response.data.thing)
  })
  .catch((error) => {
    console.log(error)
  })
Run Code Online (Sandbox Code Playgroud)

编辑:

没有ES6语法的另一种方法是在函数外部设置一个变量.即使不支持箭头功能,您在问题中提供的另一个示例也会起作用.但您也可以使用以下代码.

var self = this;
axios.get(url)
  .then(function (response) {
    self.props.handler(response.data.thing)
  })
  .catch(function (error) {
    console.log(error)
  })
Run Code Online (Sandbox Code Playgroud)

这将允许您this使用变量created(self)来访问正确的.当然,如上所述,它的缺点是它稍微笨重,并不像使用箭头功能那么干净.

有关浏览器与箭头功能兼容性的更多信息,您可以查看我可以使用.虽然如果你使用React,你很可能会使用Babel作为编译器,它应该负责转换ES6语法并使其更兼容浏览器.