【发布时间】:2021-01-11 17:41:55
【问题描述】:
我是 React.js 的新手,所以请多多包涵。
我用 react.js 构建了一个天气 API 应用程序,它可以工作。我不能做的一件事是导出我的async function fetchData(e),以便我可以从 App.js 范围之外的任何组件访问它。
如何导出异步 fetchData 以便它被 App.js 之外的所有组件识别?
请注意async function fetchData(e) 函数需要在 App.js 开头声明的所有变量。
出于显而易见的原因,我从代码中排除了我的 API 密钥,并且我没有在 fetchData 函数中包含所有代码,因为它非常冗长。
function App() {
//Variables
const API_KEY = '';
const METRE_SECOND_TO_KM_HR = 3.6;
const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
const [weather, setWeather] = useState([]);
const [geolocation, setGeolocation] = useState([]);
async function fetchData(e) {
//async function fetchData(e) {
const city = e.target.elements.city.value;
const state = e.target.elements.state.value;
const country = e.target.elements.country.value;
e.preventDefault();
//fetch request with city, state and country - to get a latitude and longitude based on city name.
const geolocation_api_request_url = `https://api.openweathermap.org/geo/1.0/direct?q=${city},${state},${country}&limit=5&appid=${API_KEY}`;
await fetch(geolocation_api_request_url)
.then(function (res) {
return res.json();
})
.then(function (data) {
if (city && state && country) {
//set the latitude and longitude of the location
setGeolocation({
data: data,
lat: data[0].lat,
lon: data[0].lon,
});
//make a second fetch call, this time with latitude and longitude
const weather_api_url = `https://api.openweathermap.org/data/2.5/onecall?lat=${geolocation.lat}&lon=${geolocation.lon}&exclude=minutely,hourly&appid=${API_KEY}&units=metric`;
return fetch(weather_api_url);
}
})
【问题讨论】:
标签: reactjs async-await weather-api