我有一個頁面,如果用戶登錄,我希望它顯示一個組件,如果未登錄,它會顯示登錄組件。
我正在嘗試使其在登錄后測驗相同的條件并自動將狀態更改為需要身份驗證的組件。
現在我在哪里,它顯示了登錄頁面。登錄后,如果單擊重繪 ,它仍然停留在登錄頁面上,但是如果我轉到另一個頁面,然后回傳,它可以作業。如何讓它始終檢查是否已登錄?
我正在嘗試使用 hook useEffect
,但我沒有實作這一點。
解決方案不一定是鉤子,可以是任何東西,我只是認為鉤子可能是解決這個問題的方法。
const Properties = () => {
const [user, setUser] = useState();
console.log(user);
useEffect(() => {
setUser(auth.currentUser);
}, [auth.currentUser]);
return (
<>
<Head>
<title>Add Property</title>
<meta name="keywords" content="web dev" />
</Head>
<h1>Add Property</h1>
<p>Welcome to the add Property new</p>
{user ? <AddProperty /> : <Login />}
</>
);
};
export default Properties;
這是登錄組件(我排除了 jsx 和不必要的位)。
onSubmit: (values) => {
console.log("onSubmit", values);
signInWithEmailAndPassword(auth, values.email, values.password)
.then((userCredential) => {
const user = userCredential.user;
console.log("user logger in");
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
},
});
uj5u.com熱心網友回復:
它不是那樣作業的。您的代碼必須監聽onAuthStateChanged
來自 firebase 的身份驗證狀態更改事件,而不是其用戶物件。
const Properties = () => {
const [user, setUser] = useState();
console.log(user);
useEffect(() => {
// you might export this as a service or something similarly.
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
setUser(user);
});
return unsubscribe;
}, []);
return (
<>
<Head>
<title>Add Property</title>
<meta name='keywords' content='web dev' />
</Head>
<h1>Add Property</h1>
<p>Welcome to the add Property new</p>
{user ? <AddProperty /> : <Login />}
</>
);
};
export default Properties;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/515652.html