如何解决无法读取未定义和未定义的属性“lat”
我现在试图通过变量 (coords)
提供用户的位置,但是每次我将任何变量传递给 onClickUserLoc() 时,该变量都会出错
无法读取未定义的属性 'lat'
当我 console.log 它指出未定义? coords 变量包含一个位置数据数组,例如 lng 和 lat,但在 onClickUserLoc() 中未定义。
代码:
export default class App extends React.Component {
constructor() {
super();
this.state = {
ready: false,where: { lat: '',lng: '' },error: null,};
this.onClickUserLoc = this.onClickUserLoc.bind(this)
}
componentDidMount() {
let geoOptions = {
enableHighAccuracy: true,timeOut: 20000,maximumAge: 60 * 60 * 24,};
this.setState({ ready: false,error: null });
navigator.geolocation.getCurrentPosition(
this.geoSuccess,this.geoFailure,geoOptions
);
}
mapRef = React.createRef();
geoSuccess = (position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
this.setState({
ready: true,where: { lat: position.coords.latitude,lng: position.coords.longitude
},});
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
};
geoFailure = (err) => {
this.setState({ error: err.message });
console.log(this.state.error);
};
onClickUserLoc({ coords }) {
this.mapRef.current.leafletElement.flyTo(coords,15);
console.log(coords);
}
render() {
const coords = [this.state.where?.lat,this.state.where?.lng];
return (
<>
<Button onPress={this.onClickUserLoc}>
<Map
center={[...]}
zoom={0}>
style={{ height: "90vh" }}
ref={this.mapRef}
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</map>
</>
)
}
解决方法
如果我理解正确,您想飞到您现在所在的位置(地理位置)。变量 coords
变量在 render 方法中定义。您可以将 coords 变量作为参数传递给按钮的 onPress :
<Button onPress={() => this.onClickUserLoc(coords)}></Button>
但你不需要在这里解构它
onClickUserLoc(coords) { // here no need to destructure it.
this.mapRef.current.leafletElement.flyTo(coords,15);
}
或者直接在 where
内部使用状态变量 onClickUserLoc
而不传递任何参数:
onClickUserLoc() {
const {
where: { lat,lng }
} = this.state;
this.mapRef.current.leafletElement.flyTo([lat,lng],15);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。