You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase onAuthStateChanged返回currentUser为null,登录路由跳转异常

Firebase Auth + React Router 路由跳转异常问题

问题描述

登录完成后尝试导航到验证页(受保护路由),但onAuthStateChanged工作异常:登录后currentUser仍为null,导致用户被错误导航到首页。该问题仅在首次登录时出现;手动在地址栏输入/verification能正常访问,此时控制台显示用户已登录。使用Firebase v10.1 + React Router 6.4。

AuthContext 代码

export default function AuthContextProvider({ children }) {
    const [currentUser, setCurrentUser] = useState(null)
    const [loading, setLoading] = useState(true)

    useEffect(() => {
        const unsubscribe = onAuthStateChanged(auth, (user) => {
            setCurrentUser(user)
            setLoading(false)
        })
        return () => {
            unsubscribe()
        }
    }, [])
}

登录函数代码

try {     
    setLoading(true)
    await login(email, pw).then(response => {
        console.log(currentUser)
        navigate('/verification')
    })
} catch(error) {
    if(error.code === "auth/user-not-found") {
        console.log(error.message)
        setError("Account does not exist. Please try again with a different email or create a new account.")
    }
    if(error.code === "auth/wrong-password") {
        console.log(error.message)
        setError("Wrong password. Please try again with a different password.")
    }
    
}     
setLoading(false)

保护路由代码

const router = createBrowserRouter(
    createRoutesFromElements(
        <Route path='/' element={<Layout />}>
            <Route exact index element={<HomePage />} />
            <Route exact path='/signup' element={<SignUp />} />
            <Route exact path='/login' element={<Login />} />
            <Route element={<ProtectedRoute />}>
              <Route exact path='/verification' element={<Verification />} />
            </Route>
            <Route path='*' element={<Error404 />} />
        </Route>
    )
);

function ProtectedRoute({children}) {
  const {currentUser} = useAuth()

  if(currentUser === null) {
    return <HomePage />
  }
  return currentUser ? <Outlet/> : <Navigate to="/" /> 
}

后续补充问题

修改保护路由代码后,登录跳转恢复正常,但未登录状态下访问/verification时,不会自动重定向到首页。需要实现:未登录用户访问验证页时自动跳转首页。

涉及路由:

  • /login
  • /signup
  • /verification

内容的提问来源于stack exchange,提问作者Ramana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:55:55