【问题标题】:How to refresh the map in react-native-maps?如何在 react-native-maps 中刷新地图?
【发布时间】:2019-01-08 18:01:36
【问题描述】:

我在我的位置跟踪应用程序中使用了react-native-maps。现在,当用户停止位置跟踪(使用按钮)时,我想用所有标记和折线清除(刷新)地图而不刷新反应组件。有没有办法做到这一点?

【问题讨论】:

    标签: react-native react-native-maps


    【解决方案1】:

    在某些时候,如果您希望在 react 中更改组件上可见的内容,除了重新渲染您的组件之外别无他法。

    我不知道react-native-maps,但我认为这个问题可以使用一般的react知识来解决。

    react-native-maps 中的标记和多边形被添加为MapView 的子级,因此根据您存储标记/线的方式,您应该能够简单地依靠 react 的状态或道具更改来更新您的@987654324 @。

    例如,如果您的标记存储在组件的状态中,您可以执行以下操作:

    class MyLocationTracker extends React.Component {
      state = { markers: [{ latlng: { latitude: 1, longitude: 1 } }] }
    
      render = () => {
        return (
          <View>
            <Text onPress={() => this.setState({ markers: [] })}>Reset markers</Text>
            <MapView>
              {this.state.markers.map((marker) => <Marker coordinate={marker.latlng} />)}
            </MapView>
          </View>
        )
      }
    }
    

    state 发生变化时,react 会再次调用render() 函数并更新标记。请注意,这也会为&lt;MapView /&gt; 组件播放小夜曲。 如果您希望避免重新渲染 &lt;MapView /&gt; 组件,您可以将逻辑移动到仅处理标记的新组件,如下所示:

    class MyLocationTracker extends React.Component {
      render = () => {
        return (
          <View>
            <Text onPress={this.markers.reset}>Reset markers</Text>
            <MapView>
              <MyMarkers ref={(comp) => { this.markers = comp }} />
            </MapView>
          </View>
        )
      }
    }
    
    class MyMarkers extends React.Component {
      state = { markers: [{ latlng: { latitude: 1, longitude: 1 } }] }
    
      reset = () => {
        this.setState({ markers: [] })
      }
    
      render = () => {
        return (
          <View>
            {this.state.markers.map((marker) => <Marker coordinate={marker.latlng} />)}
          </View>
        )
      }
    }
    

    同样,状态的变化会触发组件的重新渲染。但是现在,由于只有&lt;MyMarkers /&gt; 的状态发生了变化,它会重新渲染自己而不是其他任何东西。

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 2021-11-18
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多