2017-05-08 77 views
0

我打電話給openweathermap api來檢索higher-order組件中的天氣,然後渲染'Main'組件。但是,Ajax調用成功後,我收到以下錯誤:Promise中未定義的錯誤實現

TypeError: _getWeather2.default(...) is undefined 

代碼:

MainContainer.js:

import React from "react"; 
import getWeather from "../action/getWeather"; 
import Main from "./Main"; 

const MainContainer =() => { 
// the error is somewhere related to this component 
    var weather = getWeather("london", "uk") 
     .then((data) => { 
      console.log("data in maincontainer is...", data); 
      return <Main />; 
     }); 
} 

export default MainContainer; 

getWeather.js:

const getWeather = (city, country) => { 
    let queryPath = `http://api.openweathermap.org/data/2.5/forecast?q=${ city },${ country }&APPID=${ inserytKey }&mode=json` 
    console.log("queryPath is...", queryPath); 
    fetch(queryPath) 
     .then((response) => response.json()) 
     .then((data) => { 
      console.log("data is...", data); 
      return data; 
     }) 
     .catch((err) => { 
      console.log(err); 
     }) 
}; 

export default getWeather; 

我在做什麼錯了嗎?

+1

的GetWeather沒有返回一個承諾 –

回答

3

您的getWeather()函數不返回任何內容。你需要退還你在那裏承諾鏈所產生的承諾。

你的功能目前還在吞嚥錯誤,所以我添加了一個throw err.catch處理程序:

const getWeather = (city, country) => { 
    let queryPath = `http://api.openweathermap.org/data/2.5/forecast?q=${ city },${ country }&APPID=${ inserytKey }&mode=json` 
    console.log("queryPath is...", queryPath); 

    return fetch(queryPath) 
     .then((response) => response.json()) 
     .then((data) => { 
      console.log("data is...", data); 
      return data; 
     }) 
     .catch((err) => { 
      console.log(err); 
      throw err; 
     }) 
}; 

如果您決定不需要那麼console.log記錄的data值,你可以刪除第二個.then。同樣對於.catch():?什麼是明確的承諾,建設反模式以及如何避免]

const getWeather = (city, country) => { 
    let queryPath = `http://api.openweathermap.org/data/2.5/forecast?q=${ city },${ country }&APPID=${ inserytKey }&mode=json` 
    console.log("queryPath is...", queryPath); 

    return fetch(queryPath) 
     .then((response) => response.json()); 
}; 
+1

謝謝,這是一個令人大開眼界。我仍然對承諾感到不舒服,並會繼續深入實踐和深入研究。投票並接受了額外的感謝。 – Kayote

0

getWeather需要返回一個承諾。

const getWeather = (city, country) => { 
    let queryPath = `http://api.openweathermap.org/data/2.5/forecast?q=${ city },${ country }&APPID=${ inserytKey }&mode=json` 
    console.log("queryPath is...", queryPath); 
    return new Promise((resolve, reject) => { 
     fetch(queryPath) 
      .then((response) => response.json()) 
      .then((data) => { 
       console.log("data is...", data); 
       resolve(data); 
      }) 
      .catch((err) => { 
       reject(err); 
       console.log(err); 
      }) 
    }) 
}; 

export default getWeather; 
+0

(http://stackoverflow.com/questions/23803743/what-is - 顯式承諾 - 建設 - 反模式 - 如何做 - 我 - 避免 - 它) – JLRishe