反应在承诺中失去“这个”背景[重复]

问题描述 投票:2回答:1

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

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

这工作:

let handler = this.props.handler
axios.get(url)
  .then(function(response) {
    handler(response.data.word)
  })
  .catch(function(error) {
    console.log(error)
  })
javascript reactjs ecmascript-6 es6-promise axios
1个回答
8
投票

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

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

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

编辑:

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.