使用 Firestore 错误地输入 React Hook



我有一个自定义钩子,用于查询特定的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);

当我将鼠标悬停在钩子中的documentconst [document, setDocument] = useState上时,我看到document类型将是:

const document: firebase.firestore.DocumentData | undefined

但是,当我将鼠标悬停在组件中const [details, loading, error] = ...document上时,我看到可能的类型为:

const details: boolean | firebase.firestore.DocumentData | null | undefined

这种可能的booleannull从何而来?

我通过键入useFireStore钩子的返回来解决此问题,例如:

const useFireStore = (
collection: string,
doc: string,
loadingDelay: number = 0,
): [firebase.firestore.DocumentData | undefined, boolean, Error | null] => {
...
}

相关内容

  • 没有找到相关文章

最新更新