[英]Why data is not showing getting from firebase user in ReactJs?
I am getting user data after signin from firebase.从 firebase 登录后,我正在获取用户数据。 I am also printing it on console and it is showing that the data is here.
我也在控制台上打印它,它显示数据在这里。 But when I am trying to show it, it is not showing.
但是当我试图展示它时,它没有展示。 There is no error also.
也没有错误。 I checked the element from the browser developer tools and see there the field is empty.
我从浏览器开发人员工具中检查了该元素,发现该字段为空。 I want to show displayName, email, emailVerified .
我想显示displayName, email, emailVerified 。
Here is the image of console that is showing I am getting data:这是显示我正在获取数据的控制台图像:
My code我的代码
import React from 'react';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
const Home = () => {
// get user information
let displayName, email, emailVerified;
const auth = getAuth();
onAuthStateChanged(auth, user => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
displayName = user.displayName;
email = user.email;
emailVerified = user.emailVerified;
console.log(user);
} else {
// User is signed out
// ...
}
});
return (
<div className="container">
<div className="card w-75 mx-auto bg-warning mt-3">
<div className="card-body">
<h5 className="card-title">Name: {displayName}</h5>
<h5 className="card-title">Email: {email}</h5>
<h5 className="card-title">Verified: {emailVerified}</h5>
</div>
</div>
</div>
);
};
export default Home;
Why the data is not showing?为什么数据不显示? How can I show that data?
我怎样才能显示这些数据?
Those variables will not work that way - you need to use state in your component, see:这些变量不会那样工作 - 您需要在组件中使用 state,请参阅:
To elaborate - in functional components, the context of the function is essentially the render.详细说明 - 在功能组件中,function 的上下文本质上是渲染。 Defining them at the top of the scope there will be disconnected from where they are set in the
onAuthStateChanged
callback - the component will have already been rendered with empty values at the point that the callback is called and won't re-render.在 scope 的顶部定义它们,将与它们在
onAuthStateChanged
回调中设置的位置断开连接 - 在调用回调时,组件已经用空值呈现,不会重新呈现。
React state is what is used to handle this - and will tirgger a render when they change. React state 是用来处理这个问题的——当它们发生变化时会触发渲染。
This can be done something like:这可以这样做:
const [user, setUser] = useState();
onAuthStateChanged(auth, user => {
if (user) {
setUser(user);
} else {
// User is signed out
// ...
}
});
return (
<div className="container">
<div className="card w-75 mx-auto bg-warning mt-3">
<div className="card-body">
<h5 className="card-title">Name: {user?.displayName}</h5>
<h5 className="card-title">Email: {user?.email}</h5>
<h5 className="card-title">Verified: {user?.emailVerified}</h5>
</div>
</div>
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.