我在componentDidMount内部声明了一个变量,并且在componentDidMount内部也声明了一个函数。我试图在函数内部访问该变量,但最终出现错误。
我正在通过此组件使用此变量。我正在尝试将值分配给此变量,但无法从该函数访问它。请查看代码。
componentDidMount() {
this.weatherData = new Object();
function success(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
fetch("http://api.openweathermap.org/data/2.5/forecast?lat="+lat+"&lon="+lon+"&appid=4d0cedb0b2ae0c240bf3c08ab455915e")
.then(res => res.json())
.then(data => this.weatherData.data = data);
console.log(this.weatherData);
}
function error(err) {
alert(err.code);
}
navigator.geolocation.getCurrentPosition(success, error);
}
应将数据分配给weatherData对象。稍后,当用户将位置更改为其他城市时,我将在应用程序中更新此对象。我收到的错误是
未捕获的TypeError:成功读取失败,无法读取属性'weatherData'
和
未捕获(承诺)TypeError:无法读取未定义的属性“ weatherData”
答案 0 :(得分:0)
一个简单的解决方案是使用粗箭头功能,以便this
引用正确的对象。所以基本上:
componentDidMount() {
this.weatherData = new Object();
const success = (position) => {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
fetch("http://api.openweathermap.org/data/2.5/forecast?lat="+lat+"&lon="+lon+"&appid=4d0cedb0b2ae0c240bf3c08ab455915e")
.then(res => res.json())
.then(data => this.weatherData.data = data);
console.log(this.weatherData);
}
const error = (err) => {
alert(err.code);
}
navigator.geolocation.getCurrentPosition(success, error);
}
请注意,由于fetch
的异步特性,您的console.log将在重新分配weatherData
之前执行。它不会打印您可能期望的内容。如果要查看控制台日志的值,应将其移至then
内。