useEffect(() => {
firebase
.firestore()
.collection('likes')
.doc(slug)
.get()
.then(res => {
if (!res.data()) {
console.log('No matching document');
} else {
setLikes(res.data().likes);
}
})
.catch(err => console.log(err));
}, []);
在此處輸入圖片說明
我該如何解決錯誤。我正在嘗試重建一個使用 Firebase Cloud Functions 和 Firestore 的網路應用程式示例。
uj5u.com熱心網友回復:
使用!res.data()不會告訴 Typescriptres.data()不會回傳 undefined。
您要么必須存盤結果,然后鍵入保護它:
.then(res => { // res is a DocumentSnapshot<DocumentData>
const data = res.data(); // data is DocumentData | undefined
if (!data) {
console.log('No matching document');
} else {
setLikes(data.likes); // data is DocumentData
}
})
或者,您可以DataSnapshot#exists改用(首選):
.then(res => { // res is a DocumentSnapshot<DocumentData>
if (!res.exists) {
console.log('No matching document');
} else {
setLikes(res.data().likes); // res is treated as a QueryDocumentSnapshot<DocumentData> (res.data() always returns DocumentData)
}
})
相關API參考:
DocumentSnapshot#existsDocumentSnapshot#data()QueryDocumentSnapshot#data()
uj5u.com熱心網友回復:
因為 res.data 是一個可以回傳 undefined 的函式,所以從 typescript 的角度來看,呼叫的結果總是有可能是 undefined 的。
因此,您可以將 的結果分配給res.data()變數,然后使用它代替res.data()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369138.html
上一篇:在ReactTypescript中創建組件的constVs函式
下一篇:從表單輸入欄位更新陣列
