我试图在这个函数中获取一些位置坐标
getLocation(){
$.ajax({
url:"//freegeoip.net/json/?callback=?",
dataType:'json',
success:function (data) {
this.setState({
coordinates:data
},function () {
console.log(this.state);
})
}.bind(this),
error:function (xhr,status,err) {
console.log(err);
}
})
}
我在 componentWillMount() 阶段调用它并尝试填充这个结构。
this.state = {
restaurantsByLocations:{},
coordinates:{}
}
但是,当我尝试将其传递给
getRestaurantsByLocation(lat,longi){
/**Some code here **/
}
它不会通过。在执行 console.log() 时,我的对象已填充。但是在执行 console.log(JSON.stringify(this.state.coordinates)) 时,它显示该对象确实是空的。
这是我的 componentWillMount()
componentWillMount(){
this.getLocation();
this.getRestaurantsByLocation(this.state.coordinates.latitude,this.state.coordinates.longitude)
}
您应该做的是getRestaurantsByLocation
在setState
回调中调用您的函数。这样,与您的方法不同,您可以确保在调用函数时获得必要的信息。看起来像这样:
getLocation(){
$.ajax({
url:"//freegeoip.net/json/?callback=?",
dataType:'json',
success:function (data) {
this.setState({
coordinates:data
},function () {
this.getRestaurantsByLocation(data.latitude,data.longitude)
})
}.bind(this),
error:function (xhr,status,err) {
console.log(err);
}
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句