我对React还比较新,可能会犯一些愚蠢的错误。我正在尝试使用axios进行API调用,返回一个Promise。当这个Promise被解析后,我想将其结果传递给一个函数,通过回调在父组件上更新状态。然而,似乎'this'已经消失了,因为我得到了undefined。我猜测,由于它在未来被解决,所以不再有'this'上下文?我可以通过将回调分配给一个临时变量并使用它来解决这个问题,但感觉很笨拙。以下是代码:
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)
})