首页 > 解决方案 > 学习 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='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
          <Marker position={position} icon={myIcon}>
            <Popup>
              <span>Booyaa</span>
            </Popup>
          </Marker>
        </Map>
      )
  }
}

export default MyMap;

标签: javascriptreactjsreact-leaflet

解决方案


没有关闭})setState

问题this在于回调函数具有不同的上下文,而预计词法this应该与箭头函数一起使用:

componentDidMount() {
    navigator.geolocation.getCurrentPosition((position) => {
      this.setState({
        location: {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        }
      });
    });
}

推荐阅读