【问题标题】:Cannot get Promise values Return from api from openWeather无法从 openWeather 的 api 返回 Promise 值
【发布时间】:2018-12-16 21:42:43
【问题描述】:

我在集成 OpenWeather 的 api 时遇到了一些问题。

我可以成功记录来自 api 的响应数据值。但是当我使用 .then() 从另一个组件调用时,向我抛出错误。

以下是我用 axios 调用的 api.js

function getFiveDayForcast(cityName) {
axios.get(`http://api.openweathermap.org/data/2.5/forecast/daily?q=${cityName}&type=accurate&APPID=${apiKey}&cnt=5`)
    .then(function(response){
       // console.log("response" , response.data);
         return response.data;
    })}

module.exports= {getFiveDayForecast:getFiveDayForecast}

这是我从我的组件回调的时候

componentDidMount(){
        let  city = queryString.parse(this.props.location.search).city;
        this.makeRequest(city);
    }

    makeRequest =(city) => {
        //set loading false
        this.setState(()=> ({loading:false}));
        api.getFiveDayForecast(city).then((response) => {
            console.log(response)
        })

    }

然后它抛出

TypeError: 无法读取未定义的属性 'then'

如果有人能详细解释一下就好了。我也在阅读文档。提前致谢。

【问题讨论】:

    标签: reactjs ecmascript-6


    【解决方案1】:

    在这里发布我的答案,让更多人看到。

    参考Returning an Axios Promise from function

    抱怨是一个函数需要返回一些东西,以便then 链知道该做什么。 then 链前面的函数没有返回任何东西,所以 then 链里面的函数不知道该做什么。

    Axiosget 操作处理此问题,但您没有直接将get 方法链接到then。相反,您正在链接您创建的方法getFiveDayForcast

    您应该将getFiveDayForcast(cityName)(顺便说一句“预测”是正确的拼写)更改为

    function getFiveDayForcast(cityName) {
    
    const request = axios.get(`http://api.openweathermap.org/data/2.5/forecast/daily?q=${cityName}&type=accurate&APPID=${apiKey}&cnt=5`)
        .then(function(response){
           // console.log("response" , response.data);
             return response.data;
        })
    return request;
    }
    

    【讨论】:

      【解决方案2】:

      您需要从函数 getFiveDayForcast 返回 Promise。

      function getFiveDayForcast(cityName) {
      return axios.get(`http://api.openweathermap.org/data/2.5/forecast/daily?q=${cityName}&type=accurate&APPID=${apiKey}&cnt=5`)
          .then(function(response){
             // console.log("response" , response.data);
               return response.data;
          })
      

      }

      【讨论】:

        猜你喜欢
        • 2018-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-12
        • 2018-01-20
        • 2014-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多