React调用OpenWeatherMap API返回特殊对象无法获取数据如何解决
问题解决
根因说明
- fetch调用后返回的
res是Response类型对象,不是直接的接口返回数据,res.json()是异步方法,会返回Promise,需要等待该Promise执行完成后才能拿到真实的天气数据 - 你代码中
console.log(RES = ${res.json()})是将Promise对象直接做字符串拼接,所以输出结果为[object Promise] - axios调用返回的结果是包装后的响应对象,直接拼接字符串打印会显示
[object Object],真实数据存放在响应对象的data属性下 - 额外发现
handleChange逻辑存在错误:location状态初始为字符串类型,你用Object.assign({}, prevLocation, updatedInput)合并时,prevLocation为字符串,最终得到的createdLocation.location是undefined,会导致请求参数异常
修复代码
fetch 正确写法
const Weather = (props) => { const [weather, setWeather] = useState({}) const [location, setLocation] = useState('') // 简化输入处理逻辑,直接存储输入的地址值即可 const handleChange = event => { setLocation(event.target.value) } const handleSubmit = async (event) => { event.preventDefault() try { // 等待fetch请求完成拿到Response对象 const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${apiKey}`) // 等待Response转json完成,拿到真实天气数据 const weatherData = await res.json() console.log('获取到的天气数据:', weatherData) // 写入状态供渲染使用 setWeather(weatherData) } catch (err) { console.error('请求出错:', err) } } // 后续渲染逻辑自行补充 }
axios 正确写法
const handleSubmit = (event) => { event.preventDefault() axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${location}&appid=${apiKey}`) .then(res => { // 直接取res.data即可拿到接口返回的天气数据 console.log('获取到的天气数据:', res.data) setWeather(res.data) }) .catch(console.error) }
技术问题规范提问方式
- 明确说明开发环境:比如用到的框架版本、依赖包版本、运行环境(浏览器/小程序等)
- 清晰描述问题:包含操作步骤、实际得到的结果、你预期的结果三个核心要素
- 提供可复现的完整代码:不要只粘贴代码片段,缺失的变量可以打码标注,确保其他开发者拿到代码可以复现你的问题
- 附上完整的异常信息:比如控制台报错截图、网络请求面板的返回结果截图,打印对象时不要用字符串模板拼接,直接用
console.log(xxx)打印完整对象 - 说明你已经做过的排查尝试:比如已经确认接口返回200、调整过请求参数、查过官方文档等,避免无效沟通
内容的提问来源于stack exchange,提问作者jnr0790
相关产品推荐
相关产品推荐

