gpt4 book ai didi

javascript - Firebase getRedirectResult() 没有解决

转载 作者:行者123 更新时间:2023-12-05 03:21:20 24 4
gpt4 key购买 nike

我正在尝试实现 signInWithRedirect() 函数,但奇怪的是,它不起作用。在下面的代码中,Check 2Check 3 永远不会被记录 - 也不会抛出任何错误:

const signInWithGoogle = async () => {
try {
console.log("Check 1")
await signInWithRedirect(auth, googleAuthprovider);

console.log("Check 2")
const result = await getRedirectResult(auth);

console.log("Check 3");
if (result) {
console.log(result.user);
}

} catch (e) {
console.log(e.message.slice(10));
}
};

此外,如果我使用完全相同的 Google 帐户通过 signInWithPopup() 方法登录,一切都会按预期进行:

const signInWithGoogle = async () => {
const result = await signInWithPopup(auth, googleAuthprovider)

const user = result.user;
console.log(user)
};

我非常感谢您的帮助。谢谢!

最佳答案

signInWithRedirect 实际上会离开页面并重定向回您的应用程序,因此您需要在一个单独的函数中处理响应,该函数会在您的应用程序首次加载时触发。

import {
signInWithRedirect,
getRedirectResult,
GoogleAuthProvider,
} from "firebase/auth"
const googleAuthProvider = new GoogleAuthProvider()

// On Button Click
const signUpGoogle = async () => {
try {
await signInWithRedirect(auth, googleAuthProvider)
} catch (error: any) {
console.log(error)
}
}


// When the page loads
const debugRedirectResult = async () => {
try {
const result = await getRedirectResult(auth)
if (result) {
const details = getAdditionalUserInfo(result)
console.log(details) // details.isNewUser to determine if a new or returning user
} else {
// Everything is fine
}
} catch (error) {
console.log(error) // Debug errors from redirect response
}
}

例如,在 React 中你会做这样的事情:

// Something like an Auth context provider or App.js
React.useEffect(() => {
const debugRedirectResult = async () => {
try {
const result = await getRedirectResult(auth)
if (result) {
const details = getAdditionalUserInfo(result)
console.log(details) // details.isNewUser to determine if a new or returning user
} else {
// Everything is fine
}
} catch (error) {
console.log(error) // Debug errors from redirect response
}
}
signInWithRedirect()
}, [])

注意事项:

关于javascript - Firebase getRedirectResult() 没有解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73004241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com