我尝试从 firestore 获取文档,它返回一个空数组,但是当我运行 console.log(docs); 时 在声明的函数之外,它返回实际的数组。我知道发生此错误是因为我的 useEffect 函数在从 firestore 获取文档之前首先运行。我想知道如何解决这个问题。
const Component = (props) => {
const { docs } = useFirestore('books');
const id = props.match.params.id;
const loadContent = () => {
const book = docs && docs.filter(doc => doc.id === id);
console.log(book); //not getting book from the docs because docs is empty
}
useEffect(() => {
async function getContent(){
await loadContent();
}
getContent()
},[]);
};
useFirestore.js
import { useState, useEffect } from 'react';
import { firestore } from '../config/fbConfig';
const useFirestore = (collection) => {
const [docs, setDocs] = useState([]);
const [loading, setLoading] = useState(true);
// getting realtime data from the firebase for books
useEffect(() => {
let unsubscribe = firestore.collection(collection)
// .orderBy('createdAt', 'desc')
.onSnapshot((querySnapshot) => {
const items = [];
querySnapshot.forEach((doc) => {
items.push({...doc.data(), id: doc.id});
});
setDocs(items);
setLoading(false);
});
return unsubscribe;
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return { docs, loading };
}
export default useFirestore;
慕田峪4524236
红颜莎娜
相关分类