我試圖僅在當前用戶登錄時才顯示頁面,否則請他們登錄。我正在使用 firebase 身份驗證來實作這一點。
import Head from "next/head";
import { auth } from "../../components/firebase";
import { onAuthStateChanged } from "firebase/auth";
import Login from "../Login";
import AddProperty from "../../components/AddProperty";
const Properties = () => {
const user = 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>
{onAuthStateChanged(auth, (user) => {
if (user) {
{
<AddProperty />;
}
} else {
<Login />;
}
})}
</>
);
};
export default Properties;

uj5u.com熱心網友回復:
onAuthStateChanged回傳一個函式,該函式取消訂閱為偵聽 Firebase 身份驗證狀態而注冊的事件處理程式。您需要將經過身份驗證的用戶存盤在單獨的狀態中,并在 JSX 陳述句中使用它。
import Head from "next/head";
import { useEffect, useState } from 'react';
import { auth } from "../../components/firebase";
import { onAuthStateChanged } from "firebase/auth";
import Login from "../Login";
import AddProperty from "../../components/AddProperty";
const Properties = () => {
const [user, setUser] = useState();
useEffect(() => {
const unsubscribe = onAuthStateChanged(
auth.currentUser,
authUser => {
setUser(authUser);
}
);
return () => {
unsubscribe();
};
}, [setUser]);
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;
uj5u.com熱心網友回復:
對 Firebase 不是很熟悉,但快速瀏覽一下碼頭,并且已經熟悉 React,這是我的看法。
任何影響 React 渲染方式的資料都應該在狀態中加載,在你的情況下,是一個useState()鉤子。
此外,我基本上已經從 Firebase 檔案中直接撕掉了一個你正在嘗試做的事情的例子,并在這里使用它。靜態函式留在組件之外,因為它不會從重新渲染中受益。
import Head from 'next/head';
import { useEffect, useState } from 'react';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import Login from '../Login';
import AddProperty from '../../components/AddProperty';
const auth = getAuth();
const Properties = () => {
const [user, setUser] = useState(null);
useEffect(() => {
onAuthStateChanged(auth, user => {
if (user) {
setUser(user);
} else {
setUser(false);
}
});
}, [setUser]);
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;
此外,我不確定您希望多久從渲染中提取此用戶資料,因此此實作onAuthStateChanged()在每個渲染上運行。
希望這可以幫助。任何問題,只需發表評論,我會盡力提供幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/515654.html
標籤:Google Cloud Collective javascript反应火力基地下一个.js
上一篇:React限制了渲染的數量,以防止重新渲染過多的無限回圈
下一篇:更新陣列中的物件
