繁体   English   中英

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

[英]store each api response in an array in React

我正在使用metaweather.com API来构建Web应用程序。 我想在首页上显示6个城市; 我想我必须调用API 6次,并将数据推allCitiesDetails类似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]
    });
  }

您应该做出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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM