我试图将两个 fetch 请求合并为一个调用,以便可以在同一个数组中获取所有数据。
我尝试了 Promise.all 方法,但不确定这是否是正确的做法。
代码运作正常,我收到了数据,但是我无法理解JSON响应。
有没有更好的方法?
我尝试了 Promise.all 方法,但不确定这是否是正确的做法。
getWeather = async (e) => {
e.preventDefault();
const city = e.target.elements.city.value;
//const api_call = await
const promises = await Promise.all([
fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&APPID=${API_KEY}`),
fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&APPID=${API_KEY}`)
])
const data = promises.then((results) =>
Promise.all(results.map(r => r.text())))
.then(console.log)
代码运作正常,我收到了数据,但是我无法理解JSON响应。
(2) ["{"coord":{"lon":-5.93,"lat":54.6},"weather":[{"id"…7086601},"id":2655984,"name":"Belfast","cod":200}", "{"cod":"200","message":0.0077,"cnt":40,"list":[{"d…on":-5.9301},"country":"GB","population":274770}}"]
我应该如何设置状态?我的状态是通过一次调用设置的,就像这样:
if (city) {
this.setState({
temperature: data[0].main.temp,
city: data[0].name,
有没有更好的方法?