Reactjs 在AJAX调用后的成功回调中访问this.setState
这项工作:Reactjs 在AJAX调用后的成功回调中访问this.setState,reactjs,Reactjs,这项工作: $.ajax({ type: "POST", data: {"gender": "female"}, url: "http://localhost/something.php", dataType: "json", success: this.setState({ someKey: someValue }) }) 这不起作用(函数包装器导致This.setState丢失以前的Thi
$.ajax({
type: "POST",
data: {"gender": "female"},
url: "http://localhost/something.php",
dataType: "json",
success:
this.setState({
someKey: someValue
})
})
这不起作用(函数包装器导致This.setState
丢失以前的This
上下文)
第二种情况下的这个
就是http://localhost/something.php
要访问函数包装器中的上一个
this
上下文,我需要做什么?您需要在访问它之前调用super(),因为它直到super()才初始化调用以保持当前的上下文。此
需要绑定成功
的回调函数
最简单的方法是使用箭头函数语法:
success: () => {
this.setState({
someKey: someValue
})
}
另一个选项是使用局部变量存储该引用,并在success上使用该变量:
var that = this;
$.ajax({
type: "POST",
data: {"gender": "female"},
url: "http://localhost/something.php",
dataType: "json",
success: function() {
that.setState({
someKey: someValue
})
}
})
您需要在函数之前添加对此作用域的引用。所以var self=这个;并使用self.setStateTry使用arrow函数自动绑定
this
:success:()=>{this.setState({someKey:someValue})}
@Dekel如果您作为答案发布,我会将其标记为正确。我不敢相信箭头语法起作用了!我知道它会自动绑定上下文,但我没想到即使在这种情况下它也能工作。@iSZ你的答案有效!我更喜欢德克尔的回答。谢谢你的回答!很高兴我能提供帮助:)Super与此绑定无关,只在构造函数中使用,在构造函数中,无论如何都不应该使用ajax或任何异步。
var that = this;
$.ajax({
type: "POST",
data: {"gender": "female"},
url: "http://localhost/something.php",
dataType: "json",
success: function() {
that.setState({
someKey: someValue
})
}
})