我在Firebase身份验证状态持久性方面遇到了一个非常严重的问题,当使用单页Web应用程序时,我可以访问firebase.auth()
直到显式注销为止,现在每次重新加载时我都未定义,并且用户已注销,我正在使用它进行导航:
<HashRouter>
<Switch>
<Route exact path="/dashboard" name="Dashboard" component={DefaultLayout} />
{this.state.loggedOut ? <Route path="/" name="Home" component={Login} /> : null }
{this.state.loggedIn ? <Route path="/" name="Home" component={DefaultLayout} /> : null }
</Switch>
</HashRouter>
因此,当我登录并移至仪表板时,我会使用该功能:
login(e) {
this.setState({ loading:true });
e.preventDefault();
fire.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then((u)=>{
this.setState({ loading:false, loggedIn: true });
localStorage.setItem('AuthStatut', this.state.loggedIn);
window.location.hash = "#/Dashboard";
}).catch((error) => {
console.log(error);
});
}
一切都在第一次尝试上在仪表板上工作,看看发生了什么,我在Dashboard.js上使用了它
componentDidMount() {
const { currentUser } = fire.auth();
this.setState({ fullname: currentUser ? currentUser.displayName : 'TEST' })
}
render() {
return (
<p>{this.state.fullname}</p>
...
当我重新加载页面时,用户已注销并获得全名:TEST
我不知道为什么会这样。请有人帮助
答案 0 :(得分:1)
您必须在登录时指定持久性。
来自文档:
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(function() {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return firebase.auth().signInWithEmailAndPassword(email, password);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});