如何通过另一个API的结果发出API请求?
这是用于历史天气的应用程序。我想使用3个API,一个用于纬度和经度,另一个需要参数经度和纬度并返回附近的id站,最后一个需要第二个id站参数并返回温度。
async componentDidMount(){
axios
.get('https://api.apixu.com/v1/current.json?key=' + WEATHER_KEY + '&q=' + 'navodari')
.then(res => {
this.setState({ lat: res.data.location.lat,
lon: res.data.location.lon
});
return axios.get('https://api.meteostat.net/v1/stations/nearby?lat='+ this.state.lat+'&lon'+ this.state.lon +'&limit=1&key=' + STATION_KEY);
})
.then(res => {
this.setState({ station: res.data.id });
return axios.get('https://api.meteostat.net/v1/history/daily?station=' + this.state.station + '&start=' +this.state.start + '&end=' +this.state.start+ '&key=' + STATION_KEY);
})
.then(response => {
this.setState({ temp: response.data.temperature});
console.log(this.state.temp);
}).catch(error => console.log(error.response));
我希望使用response.data.temperature
将状态设置为temp,但这给我一个错误
工作站未定义。(“ 400错误请求”)
能否请您建议我正确的解决方案?
答案 0 :(得分:0)
如下所示,您使用async / await并在回调中为上一个setState调用下一个API,以确保状态已更新(因为状态更新也是异步的):
async componentDidMount(){
let latlongdata ,stationdata,tempdata;
try {
latlongdata = axios.get('https://api.apixu.com/v1/current.json?key=' + WEATHER_KEY + '&q=' + 'navodari')
this.setState({ lat: latlongdata.data.location.lat,
lon: latlongdata .data.location.lon
},() => {
stationdata = axios.get('https://api.meteostat.net/v1/stations/nearby?lat='+ this.state.lat+'&lon'+ this.state.lon +'&limit=1&key=' + STATION_KEY);
this.setState({ station : stationdata.data.id },() {
tempdata = axios.get('https://api.meteostat.net/v1/history/daily?station=' + this.state.station + '&start=' +this.state.start + '&end=' +this.state.start+ '&key=' + STATION_KEY);
this.setState({ temp: tempdata.data.temperature});
});
});
} catch(err) {
console.log(err);
}
}
答案 1 :(得分:0)
由Vijay Menon发布的解决方案应该可以工作,但是多次调用setState将导致多次渲染,这可能会降低效率。另外,以不同的方式使用async / await可以使代码更具可读性:
async componentDidMount(){
try {
const latlongdata = await axios.get('https://api.apixu.com/v1/current.json?key=' + WEATHER_KEY + '&q=' + 'navodari');
const lat = latlongdata.data.location.lat;
const lon = latlondata.data.location.lon;
const stationdata = await axios.get('https://api.meteostat.net/v1/stations/nearby?lat=' + lat + '&lon' + lon + '&limit=1&key=' + STATION_KEY);
const station = stationdata.data.id;
const tempdata = await axios.get('https://api.meteostat.net/v1/history/daily?station=' + this.state.station + '&start=' + this.state.start + '&end=' + this.state.start + '&key=' + STATION_KEY);
const temp = tempdata.data.temperature;
this.setState({
lat,
lon,
station,
temp
});
} catch (err) {
console.log(err);
}
}