我正在尝试找出如何在我的React挂钩中异步查询Firestore数据。
我已经看到了这个blog post,并认为我已经调整了异步调用以将其嵌套在useEffect中,但是,出了点问题。
我没有收到任何错误消息,但也没有从Firestore渲染数据。
如果删除异步提取语句,则可以在render方法中使用数据。
import React, { useState, useEffect } from 'react';
import {Link } from 'react-router-dom';
import Typography from '@material-ui/core/Typography';
import ImpactMetricsForm from "./Form";
import firebase, { firestore } from "../../../../firebase.js";
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
marginTop: '8vh',
marginBottom: '5vh'
},
}));
function useGlossaryTerms() {
const [glossaryTerms, setGlossaryTerms] = useState([])
useEffect( () => {
async function fetchGlossaryData() {
await firebase
.firestore()
.collection("glossary")
.orderBy('term')
.get()
.then(snapshot => {
const glossaryTerms = snapshot.docs.map(doc => ({
id: doc.id,
...doc.data(),
}))
setGlossaryTerms(glossaryTerms)
});
fetchGlossaryData();
};
// setRelatedGlossaryTerms(glossaryTerms)
}, [])
return glossaryTerms;
const GlossaryTerms = () => {
const glossaryTerms = useGlossaryTerms()
const classes = useStyles();
return (
<div className={classes.root}>
{glossaryTerms.map(glossaryTerm => {
{console.log('testing log of glossaryTerms', glossaryTerms)}
return (
<div key={glossaryTerm.id}>
{glossaryTerm.term}
</div>
})};
);
}
export default GlossaryTerms;
如果删除该钩子的async / await部分,则可以呈现数据。为什么我不能在异步中使用钩子?