firebase `onAuthStateChanged` 函数 returns 每次都为空

firebase `onAuthStateChanged` function returns null each time

当我在注册后调用 handleAuth 函数时,已经创建了一个用户(我可以看到他被添加到 firebase 身份验证网站),但是 onAuthStateChanged 记录为空。

我在用户成功登录后在 useEffect 中调用它。console.log(data) 在其中 returns 来自服务器响应数据的用户令牌。

为什么 onAuthStateChanged returns 为空?

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-icons/font/bootstrap-icons.css';
import { useEffect, useRef, useState } from 'react';
import useFetch from '../hooks/useFetch';
import { useLocation } from 'react-router';
import { auth } from '../config/firebaseConfig';


export default function Authenticate() : JSX.Element {
    const url = useLocation().pathname;
    const { fetchData, data, error, loading } = useFetch();

    const email = useRef() as React.MutableRefObject<HTMLInputElement>;
    const password = useRef() as React.MutableRefObject<HTMLInputElement>;
    const [show, setShow] = useState(false);

    const handleAuth = (e : React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        const path = (e.nativeEvent as any).submitter.name === 'login' ?
        `${url}/login/email` : `${url}/register`;
        fetchData(path, 'POST', {
            email : email.current.value,
            password : password.current.value
        });
    }


    useEffect(() => {
        if(data)
        {
            console.log(data)
            auth.onAuthStateChanged(user => console.log(user));
        }
    }, [data])
    
    return (
        <div className="d-flex justify-content-center align-items-center vh-100 bg-white">
            <div className="p-5 border border-2 border-success"> 
                <h1 className="fw-light fs-2 text-center">Authenticate</h1>
                <br/>
                <form onSubmit={e => handleAuth(e)}>
                    <div className="form-group">
                        <label>Email</label>
                        <div className="input-group">
                            <span className="input-group-text bi bi-person-circle"></span>
                            <input type="email" ref={email} className="form-control" placeholder="boomer@bommer.com" required/>
                        </div>
                    </div>
                    <div className="form-group">
                        <label>Password</label>
                        <div className="input-group">
                            <span className="input-group-text bi bi-key-fill"/>
                            <input type={show ? "text" : "password"} className="form-control" ref={password} placeholder="enter your password" required/>
                            <button type="button" className={`input-group-text text-decoration-none bi bi-${show ? 'eye-fill' : 'eye-slash-fill' }`} onClick={() => setShow(!show)}/>
                        </div>
                    </div>
                    <br/>
                    { error && <p className={`alert alert-danger p-1 text-center`} role="alert">{error}</p> }
                    <div className="d-flex justify-content-between">
                        <button type="submit" name="register" className="btn btn-primary" disabled={loading}>Register</button>
                        <button type="submit" name="login" className="btn btn-primary" disabled={loading}>Login</button>
                    </div>
                </form>
            </div>
        </div>
  );
}

用户的创建与使用的认证不同

创建用户时,您将存储新的用户凭据(电子邮件/密码),而在验证用户时,您会将提供的凭据与存储的凭据进行匹配。

侦听器 onAuthStateChanged 似乎安装良好,但您没有进行任何身份验证,因此它提交了一个新值:经过身份验证的 user

成功创建用户并验证其帐户后,您可以按如下方式触发登录请求:

const handleAuth = (e : React.FormEvent<HTMLFormElement>) => {
    // ...
    fetchData(path, 'POST', {
        email : email.current.value,
        password : password.current.value
    }).then(() => auth.signInWithEmailAndPassword(email.current.value, password.current.value))
}

然后注册的 onAuthStateChanged 侦听器将被正确的用户身份触发。