我正在尝试使用react进行firebase email/password auth,但出现了一个错误:
“_firebaseWEBPACK_IMPORTED_MODULE_1.default.onAuthStateChanged不是函数TypeError:_firebaseWEBPACK_IMPORTED_MODULE_1.default.onAuthStateChanged不是函数”
所以我想我的AuthContext.js代码一定有问题:
import React, { useContext, useState, useEffect } from "react";
import auth from "../firebase";
const AuthContext = React.createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState();
const [loading, setLoading] = useState(true);
function signup(email, password) {
return auth.createUserWithEmailAndPassword(email, password);
}
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password);
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
setCurrentUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
const value = {
currentUser,
login,
signup,
};
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
}
我花了三个小时才找到解决办法。可惜没有成功:(
2条答案
按热度按时间jutyujz01#
您似乎使用的是Firebase SDK版本10,它默认使用模块化语法进行API调用。因此,SDK
onAuthStateChanged
是一个顶级函数,而不是auth
服务上的方法。有关这方面的更多信息,请参阅获取当前用户的文档中的代码示例(请确保使用Web模块化API选项卡,因为您正在使用它),以及upgrading from the namespaced API to the modular API上的文档。
hgncfbus2#
问题出在导入onAuthStateChanged时。不使用auth.onAuthStateChanged(),您应该像这样导入它:
这允许您直接将onAuthStateChanged作为函数使用。您可以在Firebase文档中找到有关如何正确导入它的更多详细信息。
通过进行此更改,您将能够按预期使用onAuthStateChanged并避免错误。