我在我的App组件中有这两个方法,我想使用getLocation来设置纬度和经度,然后我想调用getWeather方法。这两种方法我想在componentDidMounth中调用
getLocation: function() {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(position){
this.setState({
location: position
});
}.bind(this)
);
}
}
和
getWeather: function() {
let latitude =48.1568806; //just for test
let longitude =17.0739704; //just for test
$.ajax({
url:`http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&APPID=${this.state.key}`,
dataType: 'json',
async: true,
cache: false,
success: function(data){
this.setState({weather: data})
}.bind(this),
error: function(e){
console.log(e);
}
});
},
但我需要等待getLocation。
我该如何处理?
答案 0 :(得分:2)
如果您需要将位置传递给getWeather
,则可以在getLocation()
componentDidMount: function() {
this.getLocation();
}
getLocation: function() {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(position){
this.setState({
location: position
});
// Add call here, change getWeather to take a location object
this.getWeather(location);
}.bind(this)
);
}
}
更多的解耦解决方案是使用promises
componentDidMount: function() {
this.getLocation().done(location=>{
this.getWeather(location);
});
},
getLocation: function() {
return new Promise((resolve, reject)=>{
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
this.setState({location: position});
resolve(location);
}.bind(this))
} else {
reject();
}
});
}
}