react-native - 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>
))
}
我的问题是当我更新数据库中的标记时(例如添加标记/设置可见 - 将道具状态更改为可见)它不会在地图上刷新,仅在我再次打开应用程序后才会显示。
有没有办法让它刷新,所以在我做出一些改变后它会在地图上呈现?
解决方案
那是因为您仅在安装组件时才从数据库中获取标记,因为您正在调用componentDidMount
. 因此,这将无法捕获对数据库的后续更改,这些更改只会在您重新加载这些组件时反映出来,这会在您“再次打开应用程序”时发生。
您可以研究的是替换get
为onSnapshot
实例化一个侦听器,它将在数据库更新时调用:https ://firebase.google.com/docs/firestore/query-data/listen
推荐阅读
- python - 在 Pandas 中将特定列的行除以 date+n
- java - 在Java中的循环内替换字符串中特定位置的字符
- javascript - 根据搜索查询更改远程 URL
- c++ - 在编译时获取文件字符串
- python - keras多层LSTM模型的股价预测收敛到一个恒定值
- amazon-web-services - 如何加快 AWS Fargate 上的部署?
- canvas - 当画布重新调整大小或滚动时,isPointInPath 中断
- anaconda - Anaconda:更新包构建,其中版本相同但构建不同
- angularjs - 想使用 angularjs 仅显示电话号码的最后 4 位数字
- php - 需要设置存储/每天的权限