Reactjs 调用引用数据类型的.get()后未呈现Firestore数据
我试图从Firestore数据库获取数据,有一个字段具有“引用”数据类型,这是我的数据结构 枪支收藏Reactjs 调用引用数据类型的.get()后未呈现Firestore数据,reactjs,google-cloud-firestore,Reactjs,Google Cloud Firestore,我试图从Firestore数据库获取数据,有一个字段具有“引用”数据类型,这是我的数据结构 枪支收藏 { "id":"...some id...", "name":"M4A1", "manufacturer":"Colt", "gun_type:"/gun_type/...some id..." (reference) } {
{
"id":"...some id...",
"name":"M4A1",
"manufacturer":"Colt",
"gun_type:"/gun_type/...some id..." (reference)
}
{
"id":"...some id...",
"name":"Assault Rifle",
"abbr":"AR"
}
枪式收集
{
"id":"...some id...",
"name":"M4A1",
"manufacturer":"Colt",
"gun_type:"/gun_type/...some id..." (reference)
}
{
"id":"...some id...",
"name":"Assault Rifle",
"abbr":"AR"
}
我想让引用像SQL数据库中的外键一样工作
这是我从firestore获取数据的代码
this.db.collection("gun").get().then((response)=>{
let newRecords = []
response.forEach((doc) => {
let data = doc.data()
// possible cause
if (data.gun_type) {
data.gun_type.get().then((res)=>{
let gunType = res.data()
newRecords.push({
id:doc.id,
gunType:gunType,
name:data.name,
manufacturer:data.manufacturer
})
})
} else {
newRecords.push({
id:doc.id,
name:data.name,
manufacturer:data.manufacturer
})
}
})
this.setState({
records:newRecords
})
}).catch((error)=>{
console.error(error)
})
然后我尝试用map()
在基本HTML表中显示记录,当我在render()
中记录return
语句之前的数据时,数据存在于this.state.records
中,但不显示在表中。控制台中没有记录错误,当我删除与gun_type
reference相关的代码时,数据显示正常。我用参考数据键做错了吗?任何答复都将不胜感激
对不起,我英语不好
--编辑--我注意到
gun\u type
引用的get()
方法也返回一个承诺,因此我不能将带有gun\u type
字段的对象推送到newRecords
数组。我目前的解决方案是setState
将每个对象直接记录到状态。我知道这不是最好的解决方案,但它是有效的。有更好的解决方案吗?当您get()获取集合或查询时,它会返回多个文档的组快照,其中每个文档都存储在docs
属性中,您可以根据需要对其进行迭代。
只需添加.docs
,forEach就可以遍历每个文档
response.docs.forEach((doc) => {
嘿,谢谢你的回复!我知道多个文档的get()
方法需要循环。但是我注意到问题是'gun_type'引用的get()
方法也返回一个承诺,我无法从那里将新对象推送到newRecords
,因此当前的解决方案是将每个文档设置为records
状态。我知道这不是最好的解决方案,但它是有效的。