【发布时间】:2021-06-03 21:10:01
【问题描述】:
我在我的 React 组件的 componentDidMount 函数中收到以下错误,我不确定原因:
未捕获的类型错误:this.setState 不是函数
我尝试绑定geocode 调用,但这似乎没有帮助。当我调用包含 setState 的本地函数时也会发生这种情况。
我已经在constructor 中绑定了componentDidMount 函数。
有人知道为什么会这样吗?
componentDidMount() {
if (this.state.initialLoad) {
navigator.geolocation.getCurrentPosition(
(position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
let geocoder = new google.maps.Geocoder();
let latlng = pos;
geocoder.geocode({
'latLng': latlng
},
function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log(results);
if (results[1]) {
let addressObject = results[1].address_components;
const cityType = 'locality';
const stateType = 'administrative_area_level_1';
let city = "";
let state = "";
for (let i = 0; i < addressObject.length; i++) {
console.log(addressObject[i]);
if (addressObject[i].types.includes(cityType)) {
city = addressObject[i].long_name;
} else if (addressObject[i].types.includes(stateType)) {
state = addressObject[i].short_name;
}
}
let isCityStateFound = city != "" && state != "";
if (isCityStateFound) {
jQuery('#city-search-ready-status').val('true');
}
let query = isCityStateFound ? city + ', ' + state : EmptyStr;
console.log(query);
jQuery('.tab-panel').find('.input-text input').val(query);
this.setState({
searchValueCity: city,
searchValueState: state
});
this.performProviderSearch();
this.performLocationSearch();
} else {
console.log('No results found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
});
}
}
【问题讨论】:
-
绑定
componentDidMount不是必需的,因为在正确的上下文中调用它以使用引用组件实例的this。但是,您的所有回调函数还必须能够访问正确的this才能工作。geocoder.geocode的回调是您的问题,可以通过使用使用词法范围的箭头函数来纠正。 -
谢谢。这行得通。这很有帮助。
标签: javascript reactjs