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

时间:2017-07-25 02:02:26

标签: javascript firebase firebase-authentication

我正在使用firebase并对路由器v4做出反应来编写我的网络应用程序。

该应用程序有两个页面:LoginPage和ProfilePage。

当用户登录时,如果用户尝试访问LoginPage,我想将用户重定向到ProfilePage。当用户未登录时,如果他们尝试访问ProfilePage,我想将用户重定向到LoginPage。

登录页面渲染方法中:

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>
        );
    }

ProfilePage 渲染方法中:

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>
        );
    }

问题: 在LoginPage中,登录并刷新页面后,currentUser为null。在我在用户名文本字段中输入内容之前,currentUser将是一个Object,它会将我重定向到ProfilePage。

期望值: 如果用户已登录,则当用户访问LoginPage时,应立即将用户重定向到ProfilePage。

1 个答案:

答案 0 :(得分:3)

问题似乎是: 刷新页面时,firebase.auth()。currentUser不会立即更新。

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

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