【问题标题】:React Native Maps ref issueReact Native Maps 参考问题
【发布时间】:2019-03-20 23:06:33
【问题描述】:

我有一个 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 Menu,导航到另一个页面,然后返回到 Map 页面。如果他们这样做,对 MapView 对象的引用将变为未定义并且 fitToCoordinates 函数将失败(TypeError: Cannot ready property 'fitToCoordinates' of undefined)。

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

【问题讨论】:

    标签: react-native react-redux react-navigation react-native-maps


    【解决方案1】:

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

    类似

    navigation.navigate({key: 'map-screen', routeName: 'Map'});
    

    【讨论】:

    • 感谢您的回复!由于导航是在 DrawerNavigator 中进行的,您是否知道您的建议是否/如何在 DrawerNavigator 中起作用?
    • 是的,当你点击抽屉里的一个项目时,上面提到的方法就会被调用。按键总是使用相同的实例调用 Map-Screen
    猜你喜欢
    • 2017-03-25
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多