将每个api响应存储在React中的数组中

时间:2018-10-17 06:40:00

标签: javascript reactjs axios

我正在使用metaweather.com API来构建Web应用程序。我想在首页上显示6个城市;我想我必须调用API 6次,并将数据推送到类似allCitiesDetails的数组中。我该怎么做?如果有更好的方法,请告诉我。这是我的代码:

state = {
    city: {
      cityname: this.props.value
    },
    woeid: '',
    todayWeather: [],
    weatherDetails: [],
    allCitiesDetails: []
  };
  getCity = (cityName) => {
    var self = this;
    axios
      .get('https://www.metaweather.com/api/location/search/?query=' + cityName)
      .then(response => {
        self.setState({
          woeid: response.data[0].woeid
        });
        self.getWeather(response.data[0].woeid);
      })
      .catch(function(error) {
        alert('No results were found. Try changing the keyword!');
      });
  }

  getWeather = async (woeid) => {
    const { data: weatherDetails } = await axios.get(
      'https://www.metaweather.com/api/location/' + woeid
    );
    this.setState({
      weatherDetails,
      todayWeather: weatherDetails.consolidated_weather[0]
    });
  }

2 个答案:

答案 0 :(得分:1)

您应该做出6个不同的承诺,并使用Promise.all并行获取所有6个城市的天气情况。您可以按照以下步骤进行操作:

const getWeatherFromWoeid = cityName => axios.get(`https://www.metaweather.com/api/location/${woeid}`);

....

const p1 = getWeatherFromWoeid(woeid1);
const p2 = getWeatherFromWoeid(woeid2);
const p3 = getWeatherFromWoeid(woeid3);
const p4 = getWeatherFromWoeid(woeid4);
const p5 = getWeatherFromWoeid(woeid5);
const p6 = getWeatherFromWoeid(woeid6);

Promise.all([p1,p2,p3,p4,p5,p6])
    .then(([result1, result2, result3, result4, result5, result6]) => {
         ...set result in the state   
    })
    .catch((err) => {
       ...handle error
    })

此外,如果您使用诺言或异步,请始终使用catch

答案 1 :(得分:0)

而不是在api调用中使用状态...

self.setState({
      woeid: response.data[0].woeid
    });

您可以将值推送到虚拟数组中,然后在api调用之外您可以设置状态。