将API数据设置为状态

时间:2019-06-13 20:10:51

标签: reactjs axios openweathermap

我正在从api中检索数据,并仅过滤出我需要的数据。我试图将检索到的对象设置为状态。

仅将最后一个对象设置为状态
axios.get('http://api.openweathermap.org/data/2.5/forecast?zip=90210&APPID=MY_KEY&units=imperial')
      .then(res => {
        var data = res.data;
        var city = res.data.city.name;

        for (var i = 0; i < data.list.length; i += 8) {
          const filteredData = {
            city,
            date: data.list[i].dt_txt,
            expectedTemp: data.list[i].main.temp,
            minTemp: data.list[i].main.temp_min,
            maxTemp: data.list[i].main.temp_max,
            description: data.list[i].weather[0].main,
            icon: data.list[i].weather[0].icon,
            id: data.list[i].weather[0].id
          };

          this.setState({ data: filteredData });
        }
        console.log(this.state.data);
      })
      .catch(err => console.log(err));

1 个答案:

答案 0 :(得分:1)

之所以只设置最后一个,是因为在每个循环中,您都覆盖了setState。您应该做的是将其保存在一个数组中,然后setState与该数组一起保存。

axios.get('http://api.openweathermap.org/data/2.5/forecast?zip=90210&APPID=badca0372074fc97fb1ceb2c2359eff5&units=imperial')
      .then(res => {
        var data = res.data;
        var city = res.data.city.name;

        let filteredDataArray = [] // data array

        for (var i = 0; i < data.list.length; i += 8) {
          const filteredData = {
            city,
            date: data.list[i].dt_txt,
            expectedTemp: data.list[i].main.temp,
            minTemp: data.list[i].main.temp_min,
            maxTemp: data.list[i].main.temp_max,
            description: data.list[i].weather[0].main,
            icon: data.list[i].weather[0].icon,
            id: data.list[i].weather[0].id
          };
          filteredDataArray.push(filteredData)  // add to the array        
        }
        this.setState({ data: filteredDataArray }); // setState with the data array
        console.log(this.state.data);
      })
      .catch(err => console.log(err));