Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 调用引用数据类型的.get()后未呈现Firestore数据_Reactjs_Google Cloud Firestore - Fatal编程技术网

Reactjs 调用引用数据类型的.get()后未呈现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) } {

我试图从Firestore数据库获取数据,有一个字段具有“引用”数据类型,这是我的数据结构

枪支收藏

{
  "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
状态。我知道这不是最好的解决方案,但它是有效的。