我试图得到一些位置坐标在此功能为什么对象未定义?
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)
}
这是一个异步调用,所以需要时间。当你使用console.log时,它会在引用发生变化时保持引用,你会看到它。当你进行串联化时,你在这个给定的时间保持这个值,并且你的状态还没有设置。编辑:你应该总是在ComponentDidMount上进行异步调用,以便在更新状态时更新视图:https://facebook.github.io/react/docs/react-component.html#componentdidmount – Nevosis
你还可以添加你的调试' console.log的问题,包括他们的结果? –
谢谢大家的解决方案!这个问题确实是异步调用,我会确保更多地教育自己。再次感谢! – LoXatoR