簡體   English   中英

如何在 nextjs 頁面中檢查身份驗證狀態

[英]How do I check auth state in a nextjs page

我不明白為什么在下面的情況下調用auth.currentUser總是返回 null。 我有另一個組件可以偵聽 auth 狀態並識別用戶已登錄(這是正確的)。

import { auth } from "../lib/firebase";

type Props = {
  hiProp: string;
};

const Index = ({ hiProp }: Props) => {
  useEffect(() => { 
    if (auth.currentUser) { // this never resolves to true
      const router = useRouter();
      router.push("/home");
    }
  }, []);

  return <div>{hiProp}</div>
}

export default Index;

export const getStaticProps = async () => {
  const hiProp = await getHiProp();

  return {
    props: { hiProp },
  };
};

當不確定是否有用戶登錄時, currentUser屬性被記錄為 null。當網頁最初加載時,它最初總是為 null - 它不會預先填充以前登錄的用戶對象。您必須使用身份驗證狀態觀察器來確定用戶對象何時首次可用,正如您所說的其他代碼正在執行的操作。

確定登錄用戶需要不確定的時間。 您可以在這篇博客文章中閱讀更多相關信息,該文章描述了為什么 currentUser 意外為 null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM