firebase.auth.currentUser 返回 null,直到在表单中输入内容



我正在使用Firebase和regram路由器v4来编写我的Web应用程序。

该应用程序有两个页面:登录页面和个人资料页面。

当用户登录时,如果用户尝试访问登录页面,我想将用户重定向到个人资料页面。当用户未登录时,如果用户尝试访问个人资料页面,我想将用户重定向到登录页面。

登录页呈现方法中:

render() {
console.log("login status: " + !!firebase.auth().currentUser);
if (firebase.auth().currentUser) {
console.log("login");
return <Redirect to='/profile' push/>
}
return (
<div className="container">
<form onSubmit={this.handleSubmit}>
<h1>Login</h1>
<label>
Username
<input type="text" value={this.state.email} onChange={(event) => this.setState({email: event.target.value})} />
</label>
<label>
Password
<input type="password" value={this.state.password} onChange={(event) => this.setState({password: event.target.value})} />
</label>
<button type="submit">Login</button>
</form>
</div>
);
}

配置文件页呈现方法中:

render() {
console.log("login status: " + !!firebase.auth().currentUser);
if (!firebase.auth().currentUser) {
console.log("profile");
return <Redirect to={'/login'} push/>
}
return (
<div><h1>Profile</h1></div>
);
}

问题:在登录页面中,登录并刷新页面后,当前用户为空。在我在用户名文本字段中输入内容之前,当前用户将是一个对象,它会将我重定向到个人资料页面。

期望:如果用户已登录,当用户访问登录页面时,它应该立即将用户重定向到个人资料页面。

问题似乎是:当我刷新页面时,firebase.auth((.currentUser 没有立即更新。

我在index.js中添加了firebase.auth((.onAuthStateChanged((方法。当身份验证状态更改时,我调用 forceUpdate(( 方法来强制组件重新渲染。

componentWillMount() {
firebase.auth().onAuthStateChanged(
(user) => {
this.forceUpdate();
console.log("onAuthStateChanged: " + !!user);
}
);
}

最新更新