javascript - 使用 react native 和 firebase firestore 计算喜欢的数量
问题描述
这是 firestore 数据结构,我可以在其中存储喜欢它的用户的 ID,但无法计算喜欢的总数。
我正在尝试计算并显示特定帖子的点赞总数,而我能够将互动存储在帖子上,但我希望总点赞数与 Insta 或 FB 帖子相同。
const onLikePress = (userId, postId) => {
firebase.firestore()
.collection("posts")
.doc(userId)
.collection("userPosts")
.doc(postId)
.collection("likes")
.doc(firebase.auth().currentUser.uid)
.set({})
}
const onDislikePress = (userId, postId) => {
firebase.firestore()
.collection("posts")
.doc(userId)
.collection("userPosts")
.doc(postId)
.collection("likes")
.doc(firebase.auth().currentUser.uid)
.delete()
}
<View style={{flexDirection:"row" , justifyContent:"space-around" , marginTop:4}}>
{ item.currentUserLike ?
(
<TouchableNativeFeedback
onPress={() => onDislikePress(item.user.uid, item.id)}
>
<MaterialCommunityIcons name="heart" size={24} color="blue" />
</TouchableNativeFeedback>
)
:
(
<TouchableNativeFeedback
onPress={() => onLikePress(item.user.uid, item.id)}
>
<MaterialCommunityIcons name="heart-outline" size={24} color="black" />
</TouchableNativeFeedback>
)
}
<TouchableOpacity onPress={() => props.navigation.navigate('Comment', { postId: item.id, uid: item.user.uid })}>
<MaterialCommunityIcons name="comment-text-outline" size={24} color="black" />
</TouchableOpacity>
<TouchableOpacity onPress={ () => onShare (item.downloadURL)}>
<MaterialCommunityIcons name="share-outline" size={24} color="black" />
</TouchableOpacity>
</View>
<Text>{item.likesCount}</Text>
</View>
解决方案
你可以使用FieldValue.increment()
它。应用到您的代码中,您所要做的就是:
const onLikePress = (userId, postId) => {
conts userPosts = firebase.firestore()
.collection("posts")
.doc(userId)
.collection("userPosts")
.doc(postId);
userPosts.collection("likes")
.doc(firebase.auth().currentUser.uid)
.set({})
.then(() => {
userPosts.update({
likesCont: firebase.firestore.FieldValue.increment(1)
});
})
}
const onDislikePress = (userId, postId) => {
conts userPosts = firebase.firestore()
.collection("posts")
.doc(userId)
.collection("userPosts")
.doc(postId);
userPosts.collection("likes")
.doc(firebase.auth().currentUser.uid)
.delete()
.then(() => {
userPosts.update({
likesCont: firebase.firestore.FieldValue.increment(-1)
});
})
}
推荐阅读
- tsql - 将 SQL Server 中的 MASTER 数据库用于数据表
- c - 为什么将 C 字符串作为 char* 传递给函数会导致运行时错误(但传递定义为 char[] 的 C 字符串是可以的)?
- javascript - Javascript原型方法与对象方法
- netlify - 十一:Netlify 不显示工作流选项卡
- git - 从新的本地仓库推送到旧的现有远程仓库
- spring-boot - 无法解析外部依赖 org.springframework.boot:spring-boot-dependencies:2.4.1 因为没有定义存储库
- apache-spark - 在具有多个值的列上加入两个 pyspark 数据框
- docker - 在此 WSL1 发行版中找不到“docker”命令
- python - Python regex 在第一个分号后切断 javascript 变量
- java - 无法从 Spring Boot Docker 容器连接 mysql Docker 容器