[英]How to get multiple Doc objects in Firebase 9 in React? and get multiple docs from firestore using its doc id?
[英]How to get a single doc info from firebase?
function AccountPage() {
const [{ patients, user }, dispatch] = useStateValue();
var therapist = '';
db.collection('therapists').doc(user.uid).get().then((snapshot) => {
therapist = snapshot.data()
console.log(therapist)
})
useEffect(() => {
console.log(therapist)
var allService = therapist.service.service[0].label
for (let i = 1; i < therapist.service.service.length; i++) {
allService += ', ' + therapist.service.service[i].label;
}
var allLanguages = therapist.language.language[0].label
for (let i = 1; i < therapist.language.language.length; i++) {
allLanguages += ', ' + therapist.language.language[i].label;
}
}, [])
我正在尝试阅读 firebase 集合中的文档。 我可以读取它并显示到控制台,但由于某种原因我无法保存数据。 如果我稍后在代码中尝试使用治疗师变量,它是未定义的。 我尝试使用 useState,但它做同样的事情,其中治疗师未定义。 我真的不明白。
尝试使用 useState,在 UseEffect 中有或没有治疗师,没有 useEffect
React 组件要记住的一点是,它们的渲染方法被认为是纯同步函数。 React function 组件的整个主体是渲染“方法”。 每次呈现AccountPage
时都声明therapist = ""
,然后开始收集 firebase 文档的无意副作用。 useEffect
挂钩在组件呈现后运行,并尝试读取空字符串值的属性,即therapist
并抛出错误。
therapist
应该是 React state 的一部分,以便它可以更新并使用获取的数据触发重新渲染。 firebase 文档应该通过useEffect
挂钩作为有意的副作用获取。
function AccountPage() {
const [{ patients, user }, dispatch] = useStateValue();
const [therapist, setTherapist] = React.useState();
// Fetch therapists document for specific user
useEffect(() => {
if (user.uid) {
db.collection('therapists').doc(user.uid).get()
.then((snapshot) => {
setTherapist(snapshot.data());
});
}
}, [user]);
// Compute services and languages when therapist state updates
useEffect(() => {
console.log(therapist);
const allService = therapist?.service?.service
.map(({ label }) => label)
.join(", ");
const allLanguages = therapist?.language?.language
.map(({ label }) => label)
.join(", ");
...
}, [therapist]);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.