我有一个自定义钩子,用于查询特定的Firebase Firestore集合/文档。
import { useContext, useEffect, useState } from 'react';
import { FirebaseContext } from 'providers/Firebase/FirebaseContextProvider';
const useFireStore = (
collection: string,
doc: string,
loadingDelay: number = 0,
) => {
const { firestore } = useContext(FirebaseContext);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [document, setDocument] = useState<
firebase.firestore.DocumentData | undefined
>();
useEffect(() => {
setLoading(true);
setDocument(undefined);
const docRef = firestore.collection(collection).doc(doc);
docRef
.get()
.then(doc => {
setDocument(doc.data());
setTimeout(() => {
setLoading(false);
}, loadingDelay);
})
.catch(e => {
setError(e);
setLoading(false);
});
}, [collection, loadingDelay, doc, firestore]);
return [document, loading, error];
};
export default useFireStore;
我是这样使用它的:
const [details, loading, error] = useFireStore('listDetails', `${id}`, 300);
当我将鼠标悬停在钩子中的document
const [document, setDocument] = useState
上时,我看到document
类型将是:
const document: firebase.firestore.DocumentData | undefined
但是,当我将鼠标悬停在组件中const [details, loading, error] = ...
document
上时,我看到可能的类型为:
const details: boolean | firebase.firestore.DocumentData | null | undefined
这种可能的boolean
或null
从何而来?
我通过键入useFireStore
钩子的返回来解决此问题,例如:
const useFireStore = (
collection: string,
doc: string,
loadingDelay: number = 0,
): [firebase.firestore.DocumentData | undefined, boolean, Error | null] => {
...
}