【发布时间】:2020-02-01 14:04:39
【问题描述】:
如何根据 ID 更新 Firestore 中的单个文档?
我想根据其 id 更新单个“公告”,但我不知道如何实现这一点。
我正在考虑是否可以将文档的 id 传递给 editFunction 并从那里根据传递的 id 更新文档。
以下是我检索数据的代码:
retrieveAnnouncement = () => {
const announcements = [];
const id = []
/* retrieve announcements */
firebase.firestore().collection('announcement').get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
announcements.push(doc.data());
//here is the unique id that I will use later on to update a single document
console.log(doc.id)
});
this.setState({ content: announcements, docID: id });
console.log(announcements)
})
.catch(err => console.log(err));
};
editSingleAnnouncement = () => {
//get the unique id of an announcement and update it.
}
在这里,它呈现来自 firestore 的数据:
_renderAnnouncement = ({ item }) =>
//display the content of announcement
<Card>
<Text h3>{item.TITLE}</Text>
<Text h5>{item.CONTENT}</Text>
<View style={styles.container}>
<Button title="Edit" containerStyle={{marginLeft: 10, width: 80}} />
<Button title="Delete" buttonStyle={{backgroundColor: 'red'}} containerStyle={{marginLeft: 10, width: 80}} />
</View>
</Card>
并渲染
render () {
return (
<View>
<ScrollView>
<FlatList data={this.state.content} renderItem={this._renderAnnouncement} keyExtractor={item => item.id} />
</ScrollView>
</View>
)}
这是我的应用程序的图像
【问题讨论】:
-
您确实需要
_renderAnnouncement函数中每个文档的ID。如果该 ID 不是您的项目的一部分,您可以将其显式传递给函数。有关示例,请参阅此问题/答案:stackoverflow.com/questions/54842905/…
标签: javascript firebase react-native google-cloud-firestore