onShow() { const selectedCity = citySelector.getCity(); // 选择城市后返回城市信息对象,若未选择返回null console.log("555", selectedCity); this.city = selectedCity.fullname this.latitude = selectedCity.location.latitude this.longitude = selectedCity.location.longitude,有一个报错 Cannot read property 'fullname' of null,怎么解决
时间: 2024-02-21 20:58:13 浏览: 154
这个错误的原因是 `selectedCity` 可能为 `null`,你需要对其进行判断,避免访问 `null` 对象的属性。你可以使用类似下面的代码进行判断:
```
onShow() {
const selectedCity = citySelector.getCity();
if (selectedCity) {
console.log("555", selectedCity);
this.city = selectedCity.fullname;
this.latitude = selectedCity.location.latitude;
this.longitude = selectedCity.location.longitude;
}
}
```
这样,当 `selectedCity` 为 `null` 时,就不会执行后面的代码,从而避免了访问 `null` 对象的错误。
阅读全文