React开发天气网站:获取IP定位后对接Openweather获取天气如何实现?
React 天气网站实现方案
核心调整点
- 新增天气数据、加载状态、错误信息三类状态,覆盖接口请求全场景
- 优化接口调用逻辑,直接在IP定位接口返回后调用天气接口,避免React state异步更新导致的参数为空问题
- 补充接口异常捕获逻辑,防止接口请求失败导致页面崩溃
- 完善OpenWeather接口参数,新增
units=metric配置返回摄氏度单位的温度数据,新增国家代码参数提升城市查询准确率 - 补充天气信息渲染逻辑
完整可运行代码
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 [weather, setWeather] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const WeatherKey = process.env.REACT_APP_WEATHERKEY; const getWeather = async (city, state, countryCode) => { if (!city || !WeatherKey) return; setLoading(true); setError(""); try { const res = await axios.get( `https://api.openweathermap.org/data/2.5/weather?q=${city},${state},${countryCode}&units=metric&appid=${WeatherKey}` ); setWeather(res.data); // 如果城市名查询不准,可以改用经纬度查询,准确率更高,替换上方接口url即可: // `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=${WeatherKey}` // lat和lon可以直接从geolocation-db的返回结果中获取 } catch (err) { setError("天气信息获取失败,请稍后重试"); } finally { setLoading(false); } }; const getData = async () => { setLoading(true); try { const res = await axios.get("https://geolocation-db.com/json/"); const { IPv4, country_name, city, country_code, state } = res.data; setIP(IPv4); setcountryName(country_name); setcityName(city); setcountryCode(country_code); setcountryStateName(state); // 定位成功后直接传参数调用天气接口,不用依赖state更新 await getWeather(city, state, country_code); } catch (err) { setError("定位信息获取失败,请稍后重试"); } finally { setLoading(false); } }; useEffect(() => { getData(); }, []); return ( <div className="IpGet"> {loading && <p>加载中...</p>} {error && <p style={{ color: "red" }}>{error}</p>} <h4>IP地址:{ip}</h4> <h4>国家:{countryName}</h4> <h4>国家代码:{countryCode}</h4> <h4>省份/州:{countryStateName}</h4> <h4>城市:{cityName}</h4> {/* 天气信息展示 */} {weather && ( <div className="weather-info"> <h3>当前天气:{weather.weather[0].main}</h3> <h4>天气描述:{weather.weather[0].description}</h4> <h4>温度:{weather.main.temp}℃</h4> <h4>体感温度:{weather.main.feels_like}℃</h4> <h4>湿度:{weather.main.humidity}%</h4> <h4>风速:{weather.wind.speed}m/s</h4> </div> )} </div> ); } export default IpGet;
注意事项
- 确保你项目根目录下的
.env文件中变量名严格为REACT_APP_WEATHERKEY,否则React将无法读取到对应的环境变量 - 修改完
.env文件后需要重启本地开发服务,新的环境变量才会生效 - 若遇到城市名查询无结果的情况,可改用经纬度查询,geolocation-db的返回结果中自带
latitude和longitude字段,直接传给OpenWeather接口即可,查询准确率更高
内容的提问来源于stack exchange,提问作者Sakula Sniper
相关产品推荐
相关产品推荐

