【问题标题】:Why is an array of documents taken from an async function empty even if I loaded it?为什么即使我加载了从异步函数中获取的文档数组也是空的?
【发布时间】:2022-01-11 13:38:13
【问题描述】:
我使用异步函数加载了一个文档数组。如果我在控制台中打印 array.length 这个值结果为 0,但如果我打印数组,我可以看到所有的值,并且它们似乎正确加载。
const array = [];
async function getArray() {
const arraySnaps = await getDocs(collection(db, "CollectionName"));
for(var i = 0; i < arraySnaps.docs.length; i++){
arrayList[i] = arraySnaps.docs[i].data();
}
return array;
}
getArray();
console.log(array.length);
console.log(array);
这是一个问题,因为我无法使用其他部分代码中的值,因为数组结果为空。
如果你需要,我也可以发布这两个日志。
【问题讨论】:
标签:
arrays
reactjs
async-await
【解决方案1】:
您必须使用 useEffect 挂钩,以便在您的组件安装后能够获取您的数据,并将此数据存储在您的组件状态中:
export default function App() {
const [array, setArray] = useState([]);
useEffect(() => {
async function getArray() {
// Fetch asynchronously the data
const arraySnaps= await getDocs(collection(db, "CollectionName"))
// Get the needed info from them
const array = arraySnaps.docs.map(doc => doc.data())
// Store it in the local state of our component
setArray(array);
}
// This function is called one time, once the component is mounted
getArray();
}, []);
// Initialy, array is an empty array, and once we fetched the data, the component will be rerended with the fetched array
console.log(array.length);
console.log(array);
}