gpt4 book ai didi

node.js - 如何在 react 应用程序中重新加载每个页面时停止 firebase re-auth()?

转载 作者:行者123 更新时间:2023-12-04 12:40:05 34 4
gpt4 key购买 nike

所以我有这个使用 firebase auth 和 firestore 的很棒的 react 应用程序。
一切正常,除了
每当我在用户已经登录的情况下重新加载页面时...导航栏链接会改变一秒钟。
看起来应用程序会在每个页面重新加载时自动重新登录(重新身份验证)用户。为什么这样?如何摆脱它?一些类似的代码示例

import React, {useState, useEffect} from 'react';
import {Switch, Route} from 'react-router-dom'
import firebase from 'firebase/App'

export const App = () => {
const [isAuth, setIsAuth] = useState()
const auth = firebase.auth()

useEffect(() => {
auth.onAuthStateChanged(user => {
if(user) {
setIsAuth(true)
} else {
setIsAuth(false)
}
})
}, [isAuth])

return(
<div className="App">
<Navbar />
<Switch>
<Route to="/signIn" component={Login} />
<Route to="/signUp" component={SignUp} />
<Route to="/signOut" component={SignOut} />
</Switch>
</div>
)
};

最佳答案

终于修好了。
发生这种情况的原因 bcoz firebase 服务器在每个页面重新加载时验证用户,这需要一些时间并导致导航栏闪烁半秒。
解决方案只需三个简单的步骤

  • 登录后,将用户存储为本地存储上的 bool 值。
     firebase.auth().onAuthStateChanged(user=>{
    if (user) {
    // store the user on local storage
    localStorage.setItem('user', true);
    } else {
    // removes the user from local storage on logOut
    localStorage.removeItem('user');
    }
    })
  • 在导航栏组件中检查本地存储中的用户
     const userLocal = JSON.parse(localStorage.getItem('user'));
    userLocal ? <SignedInLinks/> : <SignedOutLinks/>;
  • 注销时从本地存储中删除用户
  • 关于node.js - 如何在 react 应用程序中重新加载每个页面时停止 firebase re-auth()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60156164/

    34 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com