不是视图切换后的函数
Is not a function after view switch
我在使用 react-native-router-flux 切换视图时遇到 react-native 问题。
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>
);
});
}
}
我在视图之间切换后,如果我单击标注并返回,我得到错误 _this.getMarkerInfo 不是函数
"react": "^16.0.0-alpha.12",
"react-native": "^0.45.1",
"react-native-router-flux": "^3.40.1"
问题是您将 _this = this
定义为全局变量。您有可能覆盖该值,当您想在 onPress
回调中访问它时,该值指向另一个 this
引用,该引用未定义被调用的函数。
要解决此问题,请将上述代码替换为:const _this = this
;
我建议像使用 onPress
回调一样使用 ES2015 的箭头函数,您不需要自己处理这个引用。
我在使用 react-native-router-flux 切换视图时遇到 react-native 问题。
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>
);
});
}
}
我在视图之间切换后,如果我单击标注并返回,我得到错误 _this.getMarkerInfo 不是函数
"react": "^16.0.0-alpha.12",
"react-native": "^0.45.1",
"react-native-router-flux": "^3.40.1"
问题是您将 _this = this
定义为全局变量。您有可能覆盖该值,当您想在 onPress
回调中访问它时,该值指向另一个 this
引用,该引用未定义被调用的函数。
要解决此问题,请将上述代码替换为:const _this = this
;
我建议像使用 onPress
回调一样使用 ES2015 的箭头函数,您不需要自己处理这个引用。