import React from 'react';
import { useState, useEffect, useContext } from 'react';
import { auth } from '../../utils/firebase';
import AuthContext from '../../contexts/AuthContext'
//Components
import Navbar from './Navbar';
function Dashboard() {
const [email, setEmail] = useState("");
const [uid, setUID] = useState();
useEffect(() => {
console.log(auth.currentUser["email"]);
setEmail(auth.currentUser["email"]);
console.log(email);
}, []);
return (
<div>
<Navbar />
<h1>Dashboard</h1>
</div>
);
}
export default Dashboard;
你好,我正在尝试创建一个程序与react在那里我登录用户与firebase。然而,当试图从用户获取电子邮件和uid时,当我做console.log(auth.currentUser["email"])时,我能够显示数据auth.currentUser["email"],但当我试图设置状态setEmail(auth.currentUser["email"])和console.log(email) console.log不显示任何东西,我不明白为什么?我需要访问电子邮件,从用户那里获得更多的数据,所以提前谢谢你
因为state只有在组件重新呈现时才有新的值。所以你应该把console.log移到useEffect中,在组件重新渲染时检查新值。
useEffect(() => {
console.log(auth.currentUser["email"]);
setEmail(auth.currentUser["email"]);
}, []);
useEffect(() => {
console.log(email);
}, [email]);