【发布时间】:2021-11-25 02:15:40
【问题描述】:
我创建了一个异步函数来调用天气 API,该 API 将返回所提交的请求信息。该函数工作正常,但是当我在类组件中调用此函数时,结果会返回两次。这并不是一个严重的错误,但如果没有必要,我宁愿不发生两次 API 调用,我很好奇为什么这个方法首先被调用两次。
这是我的代码。
async function submitQuery(props) {
//Incase I decide to add aditional parameters such as city, country etc.. I've decided to place the zip property in an object so I can just
//add additional properties in the submissions object
const submission = {
zip: props,
};
if (!Number(props)) return console.log("this is not a number");
const { error } = await validate(submission);
if (error) return console.log(error.message);
const config = {
method: "get",
url: `https://api.openweathermap.org/data/2.5/weather?zip=${props}&appid=${apiKey}`,
headers: {},
};
/*
const query = await axios(config).then(function (response) {
const result = response.data.main;
return result;
});
*/
//console.log(query);
return 4;
}
class WeatherReport extends React.Component {
getResults = async () => {
const result = await submitQuery("08060");
console.log(result);
};
render() {
return (
<div className="reportContainer">
<WeatherCard getResults={this.getResults} />
</div>
);
}
}
const WeatherCard = ({ getResults }) => {
getResults();
return <div></div>;
};
【问题讨论】:
标签: javascript reactjs asynchronous promise