简体   繁体   English

登录后用户在刷新后注销 (React + Firebase v9)

[英]Logged-In User is logged out after refresh (React + Firebase v9)

I was setting up a dashboard project with this tutorial: https://css-tricks.com/user-registration-authentication-firebase-react/我正在使用本教程设置仪表板项目: https://css-tricks.com/user-registration-authentication-firebase-react/

Everything is fine except when I'm reloading a page: I'm always back to the login page (because I'm disconnected)一切都很好,除非我重新加载页面:我总是回到登录页面(因为我已断开连接)

I think it's an issue in this chunk of code in App.js:我认为这是 App.js 中这段代码的问题:

function App() {
  const [currentUser, setCurrentUser] = useState({})
  const [timeActive, setTimeActive] = useState(false)
  
useEffect(()  => {
    onAuthStateChanged(auth, (user) => {
      setCurrentUser(user)
     })
  }, [])
  
  return (
    <Router>
       <AuthProvider value={{currentUser, timeActive, setTimeActive}}>
      <Switch>
        <PrivateRoute exact path="/" component={Profile} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />
        <Route exact path='/verify-email' component={VerifyEmail} />
      </Switch>
      </AuthProvider>
  </Router>
  );
}

export default App;

I did some console.log inside useEffect and the output shows the state "currentUser" is empty for a moment, which I think is the reason a refresh disconnects me.我在useEffect中做了一些console.log,output显示state“currentUser”暂时为空,我认为这是刷新断开我的原因。

Do anyone knows a fix for that?有谁知道解决这个问题?

Firebase APIs load auth state asynchronously so it can take a moment for it to load. Firebase API 异步加载身份验证 state,因此可能需要一些时间才能加载。 You should use onAuthStateChanged() whenever your website loads and if the user is not logged then redirect to login and vice versa.每当您的网站加载时,您都应该使用onAuthStateChanged() ,如果用户未登录,则重定向到登录,反之亦然。 For exameple:例如:

onAuthStateChanged(auth, (user) => {
  if (user) {
    // User present
    setCurrentUser(user)
    // redirect to home if user is on /login page 
  } else {
    // User not logged in
    // redirect to login if on a protected page 
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM