【发布时间】:2021-12-18 07:39:57
【问题描述】:
我是 React 的新手,我正在尝试制作天气网站。我想先获取访问者的IP,然后获取城市位置,然后直接通过Openweather获取天气情况。这是我的代码,希望有人能帮我解答如何完成这个网站,谢谢
import { useState, useEffect } from "react";
import axios from "axios";
require("dotenv").config();
function IpGet() {
const [ip, setIP] = useState("");
const [countryName, setcountryName] = useState("");
const [cityName, setcityName] = useState("");
const [countryCode, setcountryCode] = useState("");
const [countryStateName, setcountryStateName] = useState("");
const WeatherKey = process.env.REACT_APP_WEATHERKEY;
const getData = async () => {
const res = await axios.get("https://geolocation-db.com/json/");
setIP(res.data.IPv4);
setcountryName(res.data.country_name);
setcityName(res.data.city);
setcountryCode(res.data.country_code);
setcountryStateName(res.data.state);
};
// const getWeather = async () => {
// const WeatherUrl = await axios.get(
// `https://api.openweathermap.org/data/2.5/weather?q=${cityName},${countryStateName}&appid=${WeatherKey}`
// );
// };
useEffect(() => {
getData();
}, []);
return (
<div className="IpGet">
<h4>{ip}</h4>
<h4>{countryName}</h4>
<h4>{countryCode}</h4>
<h4>{countryStateName}</h4>
<h4>{cityName}</h4>
</div>
);
}
export default IpGet;
【问题讨论】:
-
你能说得更清楚一点吗?
-
如果你想从openweather中获取基于城市的数据,你需要使用第二个
useEffect调用和[cityName]作为它的依赖数组。这样当cityName发生变化时,里面的函数就会运行。
标签: javascript reactjs api