【问题标题】:cannot display data from firestore in react app无法在反应应用程序中显示来自 Firestore 的数据
【发布时间】:2020-11-16 10:22:00
【问题描述】:

这是我第一次使用 firestore,我有一个 react 应用程序,我想在其中显示登录用户的用户名。我尝试从使用用户电子邮件查询用户的 firestore 数据库中获取用户名。

firebase.js

export const GetUserName = (email)=>{ //get single doc by email  
    let name = []; //store the name 
    //this is where the problem begins 
    db.collection('users').where("Email", "==" ,email)
         .get()
         .then(snapShot=>{
         snapShot.forEach((snap)=>{
           name.push(snap.data().userName); //stores only in array temporarily 
           console.log(name) //shows correct array 
        });
       })
       .catch(err =>{
         console.log(err);
       })
      console.log(name);  //shows empty array 
      return name[0]; //array is empty 
 }

然后我尝试在我拥有的另一个组件中显示用户名

profilePage.js

import {GetUserName} from '../firebase';

export default function ProfilePage(){
   
  const {user , logout} = useAuth(); //this is access to user.email

  return ( 
    <div>
      <h1>Hi {getUsername(user.email)} </h1> 
      <Button onClick={handleLogout} color = "primary" variant = "outlined">Log out</Button>
    </div>
  );
}

但是没有用户名我只会得到“hi”

【问题讨论】:

  • 不要使用const name = [ ] 尝试使用state variable by useState

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

由于在 return name[0] 运行时从 Firestore 异步读取用户名,因此 name.push(snap.data().userName); 尚未运行。您可以通过在这些行上设置断点并在调试器中运行代码来轻松检查这一点。

在这种情况下,您需要通过将数据置于组件的状态来将数据传递给渲染代码。使用 useState 钩子:

import {GetUserName} from '../firebase';

export default function ProfilePage(){
   
  const {user , logout} = useAuth(); //this is access to user.email
  const [userName, setUsername] = useState();

  useEffect(() => {
    db.collection('users').where("Email", "==" ,user.email)
         .get()
         .then(snapShot=>{
         snapShot.forEach((snap)=>{
           setUsername(snap.data().userName);
         });
       })
       .catch(err =>{
         console.log(err);
       })
  });

  return ( 
    <div>
      <h1>Hi {userName} </h1> 
      <Button onClick={handleLogout} color = "primary" variant = "outlined">Log out</Button>
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多