<分区>
我在理解 ES6 类中 this
的范围时遇到了一些问题。在这里,我有组件:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
credentials: {
v: '3.exp',
key: null,
},
coordinates: {
lat: 51.5258541,
lng: -0.08040660000006028,
},
};
Meteor.call('googleMapsApiKey', (err, res) => {
if (!err) {
this.setState({ key: res });
}
});
}
onMapCreated(map) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(() => {
this.setState({
coordinates: {
lat: this.lat,
lng: this.lng,
},
});
});
} else {
console.log('geolocation not supported');
}
map.setOptions({
disableDefaultUI: true,
});
}
...
我在 onMapCreated(map)
函数中的第 33 行遇到错误,特别是对 this.setState
的调用。
我怀疑我缺少某种绑定(bind),或者 this 的范围指的是 navigator.geolocation
,因此不再引用该类。大家怎么看?