这是有效的:
$.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
上下文:success: ()=> { this.setState({someKey: someValue}) }
- Dekel