React Native Maps引用问题

问题描述 投票:1回答:1

我有一个react-native-maps MapView,用于fitToCoordinates函数。该函数缩放地图以适合起点(当前用户位置)和终点。下面是MapView对象:

<MapView
      ref={map => { this.map = map; }}
      region={{
        latitude: this.props.startLatitude,
        longitude: this.props.startLongitude,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421
      }}
      style={styles.mapContainer}
      showsCompass={false}
      showsUserLocation
    >

      <MapViewDirections
        origin={{ latitude: this.props.startLatitude, longitude: this.props.startLongitude }}
        destination={this.props.optimalDestination}
        apikey={GOOGLE_API_KEY}
        strokeWidth={2}
        strokeColor={COLORS.MAIN.hexCode}
      />

      {this.walkLine()}

      {this.optimalAddressFound()}

      {this.fitCoordinates()}

    </MapView>

MapView对象中引用的fitToCoordinates函数如下:

fitCoordinates() {
if (this.props.optimalAddressFound && this.props.destinationMapFit) {
  this.map.fitToCoordinates(
    [{ latitude: this.props.startLatitude,
      longitude: this.props.startLongitude },
    { latitude: this.props.optimalAddressLat,
    longitude: this.props.optimalAddressLng }],
    { edgePadding: { top: 30, right: 30, bottom: 30, left: 30 } }
  );
 }
}

一切正常,除非用户打开React Navigation Drawer菜单,导航到另一个页面,然后返回到Map页面。如果他们这样做,则对MapView对象的引用变为未定义且fitToCoordinates函数失败(TypeError:未定义的属性'fitToCoordinates'未定义)。

我的问题是,如果我的用户导航到其他屏幕,我该如何维护地图参考?我已经尝试创建一个函数来存储我的Redux存储中的MapView对象,但似乎Redux存储不能接受Reducer中的对象。

react-native react-redux react-navigation react-native-maps
1个回答
0
投票

如果您使用react-navigation,则需要为Map-Screen设置一个键,以确保重复使用相同的屏幕,而不是每次都创建一个新屏幕。

就像是

navigation.navigate({key: 'map-screen', routeName: 'Map'});
© www.soinside.com 2019 - 2024. All rights reserved.