我正在努力通过 firebase 设置电子邮件/密码身份验证。 我已经像这样设置了 firebase 配置
// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
//authenticaion module
import "firebase/auth";
// Add the Firebase products that you want to use
import "firebase/firestore";
var firebaseConfig = {
// I've got my api key and other info copied from the console in here
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const db = firebase.firestore();
export const app = firebase.auth();
我创建了一个调用以下函数的登录表单:
import { app } from "../firebase/firebaseConfig";
const createAccount = () => {
app
.createUserWithEmailAndPassword(email, password)
.then((user) => {
console.log("user created");
console.dir(user);
})
.catch((error) => {
console.log("something went wrong");
});
};
第一个问题:我没有看到“用户已创建”消息,尽管我可以在 Firebase 身份验证控制台中看到正在创建的用户。我也没有看到表明发生异常的“出现问题”消息。
第二个问题:我试图在用户登录时进行重定向。为此,我按照文档中的建议在 Firebase auth 对象上设置了一个侦听器:
firebase.auth().onAuthStateChanged((user) => {
console.log("Inside listener");
console.dir(user);
});
问题是,我看到了控制台消息,因此该函数正在触发,但即使正在创建用户,此处的 'user' 始终为空。
Firebase 版本:8.2.1
谁能看到我在这里遗漏了什么?
答案 0 :(得分:0)
在身份验证状态侦听器中,您的回调首先使用 null
调用是正常的,因为这通常是页面加载时的初始用户身份验证状态。
Firebase 会尝试自动恢复用户的身份验证状态,但这可能需要一些时间。只有在状态恢复后,它才会再次使用当时活动的用户帐户调用您的身份验证状态侦听器。
答案 1 :(得分:0)
我找到了一个解决方案,以防有人遇到类似问题 - 触发提交的按钮位于 html 表单内,而我没有调用 event.preventDefault(),因此页面正在重新呈现,我相信这一点导致身份验证回调工作不正确。工作代码 -
const createAccount = (event) => {
event.preventDefault();
app
.createUserWithEmailAndPassword(email, password)
.then((user) => {
console.log("user created");
console.dir(user);
})
.catch((error) => {
console.log("something went wrong");
});
};