简体   繁体   English

React Firestore如何在加载时获取文档字段

[英]React Firestore how to get document field on load

I'm new to Firestore and I'm trying to get the value of displayname in a document field when the page loads so that I can place the value as a defualtValue in a TextField .我是 Firestore 的新手,我试图在页面加载时在文档字段中获取displayname的值,以便我可以将值作为defualtValue值放在TextField中。

Firestore 用户字段

import React from 'react'
import { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import { db } from '../firebase'
import { getDoc, doc} from "firebase/firestore"; 
import { TextField } from '@mui/material';

export default function EditUser() {导出默认 function EditUser() {

const { currentUser } = useAuth();

const [userData, setUserData] = useState([]);

useEffect(() =>{
    const getUsers = async()=>{
        const documentId = currentUser.uid
        const docRef =  await doc(db, "user", documentId)
        const usersCollectionRef = await getDoc(docRef)
    
        setUserData(usersCollectionRef.get("user_fields"))
        console.log(userData)
    }
    
    getUsers()
}, []);

return (
    
    <form>
        <TextField defaultValue={userData.displayname}></TextField>
    </form>
        
)

} }

but on load console.log(userData.displayname) displays undefined or an empty array但在加载时console.log(userData.displayname)显示undefined或空array

Edit: I tried making it an event by adding it in an onClick to debug it's always the first time the data doesn't show once I click it a 2-3 times it shows the data (not sure if this helps)编辑:我尝试通过将其添加到onClick中来使其成为一个事件来调试它总是第一次当我单击它时数据不显示 2-3 次它显示数据(不确定这是否有帮助)

Console Log控制台日志

The Firebase document you linked has collection "user_field s " and not "user_field".您链接的 Firebase 文档具有集合“user_field s ”而不是“user_field”。 So if you change所以如果你改变

setUserData(usersCollectionRef.get("user_field"))

to

setUserData(usersCollectionRef.get("user_fields"))

that should fix the problem那应该可以解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM