React报错求助:Uncaught TypeError: 无法读取undefined的'setState'属性
问题解决:React中调用天气API失败的修复方案
你的代码存在三个核心问题,逐一修复即可解决报错:
URL拼接错误:
原代码中+{lat}+和+{lon}+的写法会把变量包装成对象,字符串拼接后变成[object Object],导致API请求参数完全无效。直接使用变量名lat和lon即可。this指向丢失:
navigator.geolocation.getCurrentPosition的回调用了普通function,此时this不再指向组件实例,调用this.setState会触发报错。换成箭头函数就能保留组件的上下文,让this正确指向组件实例。初始状态类型不匹配:
你初始化weatherReport为数组[],但API返回的data.main是对象类型。初始设为空对象{},避免render阶段访问weatherReport.temp时因为数组没有该属性而报错。
修正后的完整代码
import React, { Component } from "react" class WeatherData extends Component{ constructor(props){ super(props); this.state ={ weatherReport: {} // 改为空对象,匹配返回数据类型 }; } componentDidMount() { // 换成箭头函数,保留组件的this上下文 navigator.geolocation.getCurrentPosition((position) => { const lat = position.coords.latitude; const lon = position.coords.longitude; // 用模板字符串拼接URL,更清晰易读 fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=xxxxxxxxxxxxxxxxxxxxxxx`) .then(response => response.json()) .then(data => this.setState({ weatherReport: data.main})); }); } render(){ const { weatherReport } = this.state; // 添加加载状态判断,避免数据未返回时页面报错 if (!weatherReport.temp) { return <div>加载中...</div>; } return( <div> {weatherReport.temp} </div> ); } } export default WeatherData;
额外说明:改用模板字符串拼接URL比加号拼接更简洁,同时在render中增加加载状态判断,能提升用户体验,避免数据未加载完成时页面出现异常。
内容的提问来源于stack exchange,提问作者Debabratta Jena
相关产品推荐
相关产品推荐

