reactjs - 使用useEffect在react-native中获取Firebase错误
问题描述
从 Firestore 中的文档获取数据以响应本机时出现错误
我使用 useEffect 来执行此操作,并且只运行一次。问题是,我第一次运行查询时它返回 Empty(我设置了一个控制台日志来检查这个)。但是,如果我从 useEffect 中删除 [] 并让它无限运行,则在第二次运行时它会获取数据。
这可能是firebase问题还是我的代码?这怎么能解决?我应该尝试运行 useEffect 2 次吗?这是怎么做的?
useEffect(() => {
firebase.firestore()
.collection("allPosts")
.where(firebase.firestore.FieldPath.documentId(), '==', props.route.params.postId)
.get()
.then((snapshot) => {
let data = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data }
})
setPost(data)
})
if (post[0]?.field) {
console.log(post[0].field)
} else {
console.log('Empty')
}
}, [])
解决方案
您应该在对 firestore 查询的检查中使用键而不是 firestore 字段值。
喜欢 :
const postId = props?.route?.params?.postId
useEffect(() => {
firebase.firestore()
.collection("allPosts")
.where('id', '==', postId)
.get()
.then((snapshot) => {
let data = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return { id, ...data }
})
setPost(data)
})
}, [postId])
- 确保密钥名称存在于 firestore 文档中。
推荐阅读
- sql-server - 对 SQL 表中的特定数据应用约束
- vba - 记住最后一个条目的 VBA 用户表单文本框
- java - 将变量从一种方法传递到另一种方法时不一致
- php - json_decode foreach 成表
- javascript - 在js中的任何数字之前将字符串分成两部分?
- php - drupal 上的可信主机模式
- python - 为什么在将 __init__.py 添加到 pytest 的测试文件夹后,我能够在调试器中导入模块
- javascript - 将值从脚本放置到 DOM
- google-apps-script - 将值从一张表复制到另一张表
- javascript - 无法在 React 上加载 javascript 组件文件