Search code examples
javascriptandroidreact-nativereact-native-router-flux

Is not a function after view switch


I have problem with react-native when switching views with react-native-router-flux.

    mapMarkerGen(){
     if(mapMarkersFetched){
     _this = this;
     return mapMarkers.map(function(marker, i){
    return(
    <MapView.Marker
      key={i}
      coordinate={{
        longitude: parseFloat(marker.lo),
        latitude: parseFloat(marker.la),
      }}
      onPress={() =>{_this.getMarkerInfo(marker.id, i);}}
      title={_this.state.title}
      description={_this.state.info}
      onCalloutPress={function(){Actions.place({placeID: marker.id});}}
    >
    </MapView.Marker>
  );
  });
}
}

After i do switch between views if i click callout and come back i get error _this.getMarkerInfo is not a function

"react": "^16.0.0-alpha.12",

"react-native": "^0.45.1",

"react-native-router-flux": "^3.40.1"


Solution

  • The problem is that you are defining _this = this as a global variable. There is a chance you overwrite the value and when you want to access it inside onPress callback, the value is pointing to a different this reference, which does not define the called function.

    To fix this, replace the aforementioned code with: const _this = this;

    I would suggest using ES2015's arrow function like you do with the onPress callback, where you don't need to handle this reference yourself.