![](/img/trans.png)
[英]Flutter: StreamBuilder gets other firestore documents when updating a single document
[英]VueJS and Firestore: Updating a document property happens twice
我有一个点击处理程序,当我点击它时,由于某种原因它会更新我的值两次(递增或递减两次)。 它不会一直发生,但我会说 90% 的时间。 我想防止这种情况并且只更新一次值。
让我解释。
首先,这是我的按钮模板代码:
<b-button
variant="link"
class="mb-2"
@click="clueHandler(comment)"
>
这是clueHandler
的脚本代码:
async clueHandler(comment) {
const inClues =
this.clues.findIndex((clue) => clue.id === comment.id) > -1
if (this.loggedIn) {
if (inClues) {
await this.$store.dispatch('removeCommentFromCluesFeed', comment)
console.log('dispatched from clueHandler')
} else if (!inClues) {
await this.$store.dispatch('addCommentToCluesFeed', comment)
console.log('dispatched from clueHandler')
}
} else {
this.$router.replace('/login')
}
},
这是 Vuex 中更新 Firestore 文档属性的逻辑:
async addCommentToCluesFeed({ state }, comment) {
try {
const cluesFeedDoc = this.$fireStore
.collection(`users/${state.userProfile.uid}/clues`)
.doc(comment.id)
await cluesFeedDoc.set(comment)
console.log('clue added from addCommentToCluesFeed action')
await this.$fireStore
.collection('comments')
.doc(comment.id)
.update({
clueVotes: parseInt(comment.clueVotes) + 1 // <<<<------------HERE !!
})
console.log('clue vote increased from addCommentToCluesFeed action')
} catch (error) {
console.error(
'error adding clue from addCommentToCluesFeed action',
error
)
}
},
这是处理程序正在更新的区域的屏幕截图:
发生的情况是,当您使用 clueHandler 在模板按钮上单击一次时,文档属性clueVotes
会递增两次(或递减两次,具体取决于用户之前是否已设置线索)。
以下是用户首次单击按钮时数据库显示的示例:
任何人对正在发生的事情或我该如何解决有任何建议或想法? 我假设这与没有完全实现承诺/比赛完成等有关。谢谢!
我找到了一个很好的解释来解释为什么我会遇到这个问题。 这是: https://fireship.io/snippets/firestore-increment-tips/
基本上,我需要返回一个可以与 set() 或 update() 一起使用的特殊值,它告诉服务器将字段的当前值增加给定值。
这是我的代码更新:
.update({
clueVotes: this.$fireStoreObj.FieldValue.increment(1)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.