javascript - 学习 React 和使用 componentDidMount 会导致错误
问题描述
谁能看到为什么下面的 componentDidMount 方法会导致错误?如果 componentDidMount 方法被移除,则地图加载时不会出错。
错误消息如下所示。在浏览器(chrome 工具)中查看代码时,未设置“this”,因此会导致错误。
违规方式
componentDidMount() {
navigator.geolocation.getCurrentPosition(function(position) {
this.setState({
location: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
});
}
错误信息
Line 35: Parsing error: Unexpected token, expected ","
const position = [this.state.location.lat, this.state.location.lng]
完整代码
import React from 'react'
import L from 'leaflet'
import { Map, Marker, Popup, TileLayer } from 'react-leaflet'
var myIcon = L.icon({
iconUrl: 'images/maps-icon-12.png',
iconSize: [25, 41],
iconAnchor: [12.5, 41],
popupAnchor: [0, -41]
});
class MyMap extends React.Component {
constructor () {
super()
this.state = {
location: {
lat: 10.7268906,
lng: -30.3580425,
},
zoom: 13
}
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(function(position) {
this.setState({
location: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
});
}
render () {
const position = [this.state.location.lat, this.state.location.lng]
return (
<Map center={position} zoom={this.state.zoom}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position} icon={myIcon}>
<Popup>
<span>Booyaa</span>
</Popup>
</Marker>
</Map>
)
}
}
export default MyMap;
解决方案
没有关闭})
。setState
问题this
在于回调函数具有不同的上下文,而预计词法this
应该与箭头函数一起使用:
componentDidMount() {
navigator.geolocation.getCurrentPosition((position) => {
this.setState({
location: {
lat: position.coords.latitude,
lng: position.coords.longitude
}
});
});
}
推荐阅读
- xamarin.android - 在 Xamarin 本机项目中使用 SkiSharp
- mysql - Flask 和 MySQL 的 Gitlab Yaml 设置示例
- python - 将列表列表中的罗马数字转换为整数
- java - Java 前导零的 Parseint
- swiftui - SwiftUI 嵌套 ForEach
- c++ - 在编译时根据一些枚举值添加额外的方法
- firebase - 在 Unity3D 中检查 Firebase 是否初始化成功?
- python - 如何动态构建函数并找到根python
- java - 反转类中的数组不会改变元素的顺序
- csv - 如何打开具有多列和多行的大型 CSV 文件