如何将API获取的地理定位城市传入React useState状态替换默认值
解决步骤
1. 修正GeoLocation函数的错误写法
你当前的GeoLocation函数内直接调用了useGeolocation这个React Hook,不符合Hook的使用规则:Hook只能在组件顶层或者自定义Hook中调用,不能在普通异步函数里调用,所以先改造这个函数,让它接收经纬度作为参数,并且返回获取到的城市名:
// 改造后的定位取城市函数,接收经纬度作为入参,返回城市名称 export const getCityByGeo = async (latitude, longitude) => { const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`; const res = await axios.get(url); return res.data.name; }
2. 调整定义city状态的组件逻辑
你需要在该组件内调用useGeolocation获取经纬度,再调用上面的接口拿城市名,最后触发setCity更新状态:
首先修改状态初始值,建议默认设为空,定位失败再 fallback 到默认城市'Turi':
// 把useGeolocation移到组件顶层调用 const geolocation = useGeolocation(); // 初始值先设为空,定位完成后自动更新 const [city, setCity] = useState('');
然后新增组件挂载时的定位获取逻辑,添加一个useEffect:
// 新增useEffect,拿到有效经纬度后自动请求定位城市,更新state useEffect(() => { // 经纬度有效时才发起请求 if (!geolocation.latitude || !geolocation.longitude) return; const fetchLocationCity = async () => { try { const locationCity = await getCityByGeo(geolocation.latitude, geolocation.longitude); setCity(locationCity); } catch (err) { // 定位或者接口请求失败时,回退到默认城市Turi setCity('Turi'); } } fetchLocationCity(); }, [geolocation.latitude, geolocation.longitude]);
3. 原有业务逻辑无需调整
你现存的所有调用city的逻辑(包括handleCityWeather、handleForeCast以及监听city变化的两个useEffect)都不需要改动,它们已经绑定了city状态的更新,只要setCity触发,后续的天气、预报请求都会自动执行。
内容的提问来源于stack exchange,提问作者user8248285
相关产品推荐
相关产品推荐

