React 在 promise 中丢失 'this' 上下文

react loses 'this' context inside promise

我对 React 很陌生,可能犯了一个愚蠢的错误。我正在尝试使用 returns 承诺的 axios 进行 api 调用。当这个承诺解决时,我想将它的结果传递给一个函数,该函数通过回调更新父级的状态。但是,当我未定义时, 'this' 似乎消失了。我想随着它在未来的解决,不再有 'this' 上下文?我可以通过将回调分配给 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)
  })

这就是箭头函数的用武之地。箭头函数基本上维护上面的 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)
  })

这样您就可以使用创建的变量 (self) 访问正确的 this。当然,如前所述,它的缺点是它稍微笨重一点,不像使用箭头函数那样干净。

有关浏览器与箭头函数兼容性的更多信息,您可以查看 Can I use。尽管如果您正在使用 React,您很有可能会使用 Babel 作为编译器,它应该负责转换 ES6 语法并使其与浏览器更加兼容。