英文:
Fireabase snapShot is not working on react typescript
问题
以下是您要翻译的内容:
我最近在学习React和Firebase。我遇到了这个问题,已经有2天了,但我还是无法解决它。当我从Firebase中检索数据时,使用snapShot
时出现错误。
以下是代码:
const fetchData = async () => {
const result = await getDocs(collection(db, "post"));
onSnapshot(result, (snap: any) => {
const newArray: any[] = [];
snap.forEach((doc: any) => {
if (doc !== newArray) {
newArray.push({ title: doc.data().title, content: doc.data().content, user_id: doc.data().user_id, id: doc.id });
}
});
setPost([...post, newArray]);
});
}
以下是我的错误信息:
TS2769:没有匹配此调用的重载。最后一个重载产生了以下错误。
参数类型为'QuerySnapshot'无法分配给类型'Query '。
类型'QuerySnapshot'缺少类型'Query '的以下属性:converter、type、firestore、withConverter
请帮助我,我对TypeScript还很陌生(尽管我之前用过Angular,但React对我来说是相对较新的,Firebase也是)。
英文:
I am recently learning the React, and firebase. I've encountered this problem for like 2 days still I can't solve it. There is an error when I use snapShot from firebase when I am retrieving something.
Here is the code:
const fetchData = async () => {
const result = await getDocs(collection(db, "post"))
onSnapshot(result, (snap:any) => {
const newArray:any[] = [];
snap.forEach((doc:any) => {
if(doc !== newArray){
newArray.push({title: doc.data().title, content: doc.data().content, user_id:doc.data().user_id, id: doc.id})
}
});
setPost([...post, newArray]);
});
}
Here is my error:
> TS2769: No overload matches this call. The last overload gave the
> following error.
> Argument of type 'QuerySnapshot<DocumentData>' is not assignable to parameter of type 'Query<unknown>'.
> Type 'QuerySnapshot<DocumentData>' is missing the following properties from type 'Query<unknown>': converter, type, firestore,
> withConverter
Please help me, I am new to Typescript (although I face angular before React is quite new to me, and so does firebase)
答案1
得分: 2
onSnapshot()
函数的第一个参数应该是 DocumentReference 或 CollectionReference,但你正在传递一个 QuerySnapshot。在使用监听器之前,你不需要显式地获取文档。尝试以下代码:
const fetchData = async () => {
const colRef = collection(db, "post");
onSnapshot(colRef, (snap: any) => {
// ... 处理响应
});
}
英文:
The onSnapshot()
function takes either a DocumentReference or a CollectionReference a first parameter but you are passing a QuerySnapshot. You don't have to fetch document explicitly before using a listener. Try:
const fetchData = async () => {
const colRef = collection(db, "post");
onSnapshot(colRef, (snap: any) => {
// ... handle response
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论