首页 > 解决方案 > React Native:如何在地图上更新标记?

问题描述

我有一类地图,我从数据库中获取标记并将它们映射到地图屏幕上。我正在尝试显示在 DB 中更改但仅在刷新应用程序时才起作用的新标记。

一些代码:

componentDidMount() {
   
   ... 
})
// get markers from DB
    markerRef.get()
    .then(querySnapshot => {
      // console.log('Total users: ', querySnapshot.size);
      const markers = [];
      // if(querySnapshot)
      querySnapshot.forEach(res => {
        const {title, info, latitude, longitude, imageUri} = res.data()
        markers.push({
          latitude,
          longitude,
          title,
          info,
          imageUri,
          id: res.id
        })
      });
      this.setState({
        markers,
      })
    });
    

  }

在我的渲染中,我映射了标记:

  this.state.markers.map(marker => (
          //  <<<<~~~~ I think those 2-3 lines are matter
          <MapView.Marker
            key={marker.id}
            coordinate={{longitude: marker.longitude, latitude: marker.latitude}}
            onPress={(e)=>this.onMarkerPress(e, marker)} //
            >
            
              <MapView.Callout tooltip
                      onPress={() => this.setState({infoModal: 'true', markerUrl: marker.imageUri})}
              
              >
                <View style={{backgroundColor: 'white'}} >
                      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> 
                        {/* {marker.imageUri &&  <Image source = {{uri:marker.imageUri}} //{{uri: marker.imageUri}}
                        style = {{ width: '90%', height: 200, justifyContent: 'center', flex: 1,}}
                        resizeMode="center"
                      /> }         */}
                      </View>
                    <Text>Lat: {marker.latitude}, Lon: {marker.longitude}</Text>
                    <Text>{marker.email}</Text>
                    <TouchableOpacity onPress={() => this.setState({infoModal: 'true', markerUrl: marker.imageUri})}>
                      <Text style={{color: 'blue'}}> info </Text>
                    </TouchableOpacity>
                </View>
              </MapView.Callout>         
          </MapView.Marker>
        ))
      }

我的问题是当我更新数据库中的标记时(例如添加标记/设置可见 - 将道具状态更改为可见)它不会在地图上刷新,仅在我再次打开应用程序后才会显示。

有没有办法让它刷新,所以在我做出一些改变后它会在地图上呈现?

标签: react-nativereact-native-maps

解决方案


那是因为您仅在安装组件时才从数据库中获取标记,因为您正在调用componentDidMount. 因此,这将无法捕获对数据库的后续更改,这些更改只会在您重新加载这些组件时反映出来,这会在您“再次打开应用程序”时发生。

您可以研究的是替换getonSnapshot实例化一个侦听器,它将在数据库更新时调用:https ://firebase.google.com/docs/firestore/query-data/listen


推荐阅读