gpt4 book ai didi

reactjs - AJAX 调用后在成功回调中访问 this.setState

转载 作者:行者123 更新时间:2023-12-03 14:13:27 25 4
gpt4 key购买 nike

这有效:

$.ajax({
type: "POST",
data: {"gender": "female"},
url: "http://localhost/something.php",
dataType: "json",
success:

this.setState({
someKey: someValue
})

})

这不起作用(函数包装器会导致 this.setState 丢失之前的 this 上下文)

$.ajax({
type: "POST",
data: {"gender": "female"},
url: "http://localhost/something.php",
dataType: "json",
success: function(){ // function wrapper begins

this.setState({
someKey: someValue
})
} // function wrapper ends
})

第二种情况下的this结果是http://localhost/something.php

我需要做什么才能访问函数包装器内先前的 this 上下文?

最佳答案

为了保留当前this的上下文,您需要绑定(bind)success的回调函数。

最简单的方法是使用箭头函数语法:

success: () => {
this.setState({
someKey: someValue
})
}

另一种选择是使用局部变量来存储该引用,并在成功时使用该变量:

var that = this;
$.ajax({
type: "POST",
data: {"gender": "female"},
url: "http://localhost/something.php",
dataType: "json",
success: function() {
that.setState({
someKey: someValue
})
}
})

关于reactjs - AJAX 调用后在成功回调中访问 this.setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com