![](/img/trans.png)
[英]NextJS, Typescript -> Write Data to Google Cloud Firestore Map (nested object)
[英]Unable to map data of nested firebase/firestore query, React & Typescript
我試圖通過首先從 firestore 中獲取數據來呈現部分和部分內的講座數據,其中講座也保存在部分內。 我的方法是先查詢section 集合,然后使用section id 查詢它的lectures 集合。
在控制台中,我可以看到部分數據和嵌套講座數據的正確輸出。 在網頁上我沒有顯示嵌套的講座數據,但在保存代碼更改時,它們有時會 flash 持續 0.1 秒。
我假設這指出了由於嵌套查詢的異步性質而導致的重新呈現問題,但我發現異步函數非常混亂,而且似乎無法找到一種方法讓它們按我預期的方式運行。
import React, {useState, useEffect} from 'react'
import { db } from '../../../firebase-config'
import {collection, onSnapshot, query} from 'firebase/firestore'
type CourseSections = CourseSection[]
type CourseSection = {
id: string,
title: string,
lectures: CourseLectures,
}
type CourseLectures = CourseLecture[]
type CourseLecture = {
title: string,
id: string,
}
const Test2:React.FC = () => {
const [data, setData] = useState<CourseSections>([])
useEffect(()=>{
async function fetchData() {
const q = query(collection(db, "products", "5yzLggfe5YC0PAM49enW", "sections"))
onSnapshot(q, (snapshot)=> {
let tempSections:CourseSections = []
snapshot.docs.forEach((doc:any)=>{
const w = query(collection(db, "products", "5yzLggfe5YC0PAM49enW", "sections", doc.id, "lectures"))
let tempLectures:CourseLectures = [];
onSnapshot(w, (snapshotB:any)=>{
snapshotB.docs.forEach((doc:any)=>{
tempLectures.push({...doc.data(), id: doc.id})
})
})
tempSections.push({...doc.data(), id: doc.id, lectures: tempLectures}) //
})
setData(tempSections)
})
}
fetchData();
}, [])
return <>
{data.map((section:CourseSection)=>{
return <><h2>{section.title}</h2>
{section.lectures.map((lecture:CourseLecture)=>{
return <h4>{lecture.title}</h4>
})}
</>
})}
</>
}
export default Test2
在閱讀以下帖子的答案后,我最終找到了解決問題的方法:
有沒有辦法在查詢主集合時將 map 子集合轉換為結構? (消防站)
因此,我現在不是查詢集合並立即查詢其子集合,而是將子集合中的數據保存在包含地圖數組的字段中。 這樣我就可以在一個查詢中訪問所有數據,而不需要嵌套查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.