如何在具有功能组件的React应用中使用Google(通过Firebase)登录用户?

问题描述 投票:0回答:1

我正在尝试在我的React / Firebase应用中使用Google登录用户。我遵循了YouTube(https://www.youtube.com/watch?v=umr9eNbx3ag)上的教程,但结果不同。当我单击“登录”按钮时,我将重定向到Google,选择一个帐户,然后重定向到我的网站。

好像我的'if'语句永远不会运行,auth.currentUser永远都不会评估为真。

这是我的Firebase文件

firebase.initializeApp(firebaseConfig)
export const firestore = firebase.firestore()
export const auth = firebase.auth()
export const provider = new firebase.auth.GoogleAuthProvider()
export const signInWithGoogle = () => auth.signInWithRedirect(provider)
export const signOut = () => auth.signOut()
export default firebase

这是我的登录组件

import { auth, signInWithGoogle, signOut } from '../../Firebase/Firebase'

const LoginOrRegister = () => {

  const { username, setUsername, idToken, setIdToken } = useContext(Context)

  useEffect(() => {
    auth.onAuthStateChanged(async nextUser => {
      if (auth.currentUser) {
        setIdToken(await auth.currentUser.getIdToken())
        setUsername(auth.currentUser.displayName)
      } else {
        setIdToken(null)
      }
    })
  }, [])

return (
  <div>
    <LogInForm>
    <button onClick={signInWithGoogle}> Log in with Google </button>
  </div>
)
reactjs firebase oauth
1个回答
0
投票

由于您正在使用signInWithRedirect,因此您实际上需要离开应用程序并返回[]时,需要使用auth.getRedirectResult()而不是[C0

下面的代码将对您有用。

auth.onAuthStateChanged

您可以找到参考文献useEffect(() => { auth .getRedirectResult() .then(function(result) { console.log(result); if (result.credential) { // This gives you a Google Access Token. You can use it to access the Google API. var token = result.credential.accessToken; setToken(token); // ... } // The signed-in user info. var user = result.user; console.log(user); setData(user); }) .catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. console.log(errorCode, errorMessage); // ... }); }, []);

© www.soinside.com 2019 - 2024. All rights reserved.