React中发起新API调用时如何复用相同对象格式更新状态?
解决方案
你可以把重复的请求逻辑和返回数据格式化逻辑抽成独立的公共函数,所有需要调用天气接口的场景直接复用这个函数即可,后续需要调整字段时也只需要修改一处代码。
步骤1:抽离公共天气请求方法
在组件内新增一个通用的异步请求函数,接收查询参数(支持经纬度字符串、城市名两种格式),统一处理接口请求和数据格式化,返回符合weatherData结构的对象:
// 参数q:传经纬度(格式为`${lat},${lon}`)或者城市名均可 const fetchWeather = async (q) => { const response = await axios.get(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${q}`); const results = response.data; // 统一处理数据格式,仅需编写一次 return { name: results.location.name, country: results.location.country, region: results.location.region, temperature: results.current.temp_c, description: results.current.condition.text, icon: results.current.condition.icon, humidity: results.current.humidity, }; };
步骤2:改写原有两个场景的调用逻辑
- 页面加载时根据定位获取天气:
if (lat !== 0 && lon !== 0) { const fetchData = async () => { setLoading(true); try { const weatherResult = await fetchWeather(`${lat},${lon}`); setWeatherData(weatherResult); } catch (error) { // 可统一加错误提示逻辑 console.error('定位获取天气失败:', error); } finally { setLoading(false); } }; fetchData(); }
- 搜索城市时调用:
const handleSearch = async (e) => { e.preventDefault(); if (search === '') return; setLoading(true); try { const weatherResult = await fetchWeather(search); setWeatherData(weatherResult); } catch (error) { console.error('搜索城市天气失败:', error); } finally { setLoading(false); } };
额外优化建议
如果后续其他组件也需要调用天气接口,可以把这个fetchWeather函数抽到项目公共工具文件(比如/src/utils/weather.js)中,全局复用。
内容的提问来源于stack exchange,提问作者iHopeiGetit
相关产品推荐
相关产品推荐

