1

I'm having some trouble understanding the scope of this inside of ES6 classes. Here, I have component:

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,
    });
  }

...

I get a error on line 33, which is in the onMapCreated(map) function, specifically the call to this.setState.

enter image description here

I suspect I'm missing sort of binding, or that the scope of this refers to navigator.geolocation and therefore no longer references the class. What do you guys think?

ilrein
  • 3,833
  • 4
  • 31
  • 48
  • Related: [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling Apr 07 '16 at 15:54

1 Answers1

3

It's not the issue of ES6, it's the binding issue or React. You should bind your method in the constructor of React:

this.onMapCreated = this.onMapCreated.bind(this);

So that this can be recognized in your method.

Well, maybe it's the issue of ES6, see this docs of React:

With React, every method is automatically bound to its component instance (except when using ES6 class syntax).

Qianyue
  • 1,767
  • 19
  • 24