继续兑现我以前的承诺

时间:2020-08-07 13:55:06

标签: javascript reactjs api axios

    this.state = {
      city: null,
      cityNumber : null,
      typeWeather: "",
      minTemp: 0,
      maxTemp: 0,
      theTemp: 0
    };
  }


  SearchingCity = (city) => {
    return new Promise(resolve => {
      axios.get(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/search/?query=${city}`)
      .then((result) => {
        let cityName = result.data[0].woeid;
            this.setState({
              city: cityName
            });
            resolve(cityName)
      })
    })
  }

  getCityID = async () => {
    const cityID = await this.SearchingCity();
    console.log(cityID)
    this.setState({
      cityNumber : cityID
    })
    const thisID = this.state.cityNumber;
    axios.get(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/${thisID}`)
    .then((result) => {
      const type_Weather = result.data.consolidated_weather[0].weather_state_name
      const min_Temp = result.data.consolidated_weather[0].min_temp
      const max_Temp = result.data.consolidated_weather[0].max_temp
      const the_Temp = result.data.consolidated_weather[0].the_temp

      this.setState({
        typeWeather : type_Weather,
        minTemp : min_Temp,
        maxTemp : max_Temp,
        theTemp : the_Temp
      })
    })
  }

所以在console.log(cityID)中,它应该是 SearchingCity 方法的结果,但是 当我console.log(cityID)时,得到的结果为空,应该更改的部分在哪里?

谢谢你们

1 个答案:

答案 0 :(得分:0)

@gbalduzzi 指出的那样, 问题在这里,

const cityID = await this.SearchingCity();
//                                     ^^

您未根据需要使用任何SearchingCity参数调用city

  SearchingCity = (city) => {
//                ^^^^^^