简体   繁体   中英

Learning React and using componentDidMount causes an error

Can anyone see why the following componentDidMount method causes an error please? If the componentDidMount method is removed the map loads without error.

The error message is shown below. When looking at the code in the browser (chrome tools) the 'this' is not set and hence causes an error.

Offending method

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

Error message

Line 35:  Parsing error: Unexpected token, expected ","
    const position = [this.state.location.lat, this.state.location.lng]

Complete code

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;

There's no closing }) for setState .

The problem with this is that callback function has different context, while it's expected that lexical this should be used with arrow function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM