繁体   English   中英

Firebase 和 React TypeError: firebase.auth(...).onAuthStateChanged 不是 function

[英]Firebase and React TypeError: firebase.auth(...).onAuthStateChanged is not a function

我正在尝试使用 onAuthStateChanged 触发器取消订阅,但我不断收到:

Uncaught TypeError: (0, firebase_util__WEBPACK_IMPORTED_MODULE_0 _.getModularInstance)(...).onAuthStateChanged is not a function 下面是我的 Authcontext.js

import React ,{useEffect, useState ,useContext} from 'react';
import { auth } from '../api/firebase';
    
const AuthContext = React.createContext();    

export function useAuth() {
    return useContext(AuthContext)
}

export function AuthProvider({ children }) {
    const [currentUser, setCurrentUser] = useState(null);        
    const [loading,setLoading] = useState(true);
    
    function register (email,password) { 
        return auth.createUserWithEmailAndPassword(email,password);
    }
    
    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user);
        });
        return unsubscribe;
    }, []);
    
    const value = {
        currentUser,
        register,
    }
    
    return (
        <AuthContext.Provider value={value}>
            {children}
         </AuthContext.Provider> 
    );
}

您没有正确订阅 StateChange,请尝试以下操作

React.useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => { // detaching the listener
        if (user) {
            // ...your code to handle authenticated users. 
        } else {
            // No user is signed in...code to handle unauthenticated users. 
        }
    });
    return () => unsubscribe(); // unsubscribing from the listener when the component is unmounting. 
}, []);

我在处理本机应用程序时遇到了同样的错误,并且由于 firebase 版本更改,他们更新了一些方法。

我已经通过下面的代码解决了这个问题,firebase 版本是 ^9.6.11。 你不需要拉onAuthStateChanged

import { getAuth } from "firebase/auth";

export const yourfunc = () => {   
 const auth = getAuth(); 
 auth.onAuthStateChanged((user) => {
 console.log(user)
 } 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM