我正在调用 openweathermap api 来检索 higher-order
组件中的天气,然后渲染“Main”组件。但是,ajax调用成功后,出现以下错误:
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;
我做错了什么?
最佳答案
您的 getWeather()
函数不会返回任何内容。您需要返回由您那里的 promise 链生成的 promise 。
您的函数当前也在吞没错误,因此我在您的 .catch
处理程序中添加了一个 throw err
:
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( ));
};
关于javascript - promise 履行中的未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43850969/