首页 > 解决方案 > FireBase getAuth 和 onAuthStateChanged 不在“firebase/auth”导入中

问题描述

我正在尝试学习和使用“firebase/auth”中的 getAuth()、onAuthStateChanged() 方法但是在 node_modules/firebase/auth 的文件夹中不包括这些方法。似乎根据firebase的版本更改目录。我的依赖:

"dependencies": {
    "antd": "^4.16.13",
    "firebase": "^9.0.2",
    "next": "11.1.2",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },

通过firebase doc它说我应该使用import { getAuth, onAuthStateChanged } from "firebase/auth"; 我搜索并发现该"firebase/firebase-auth";文件夹包含getAuth方法但是当我尝试使用import {getAuth} from "firebase/firebase-auth";它时给我一个错误状态firebase/firebase-auth文件未导出。

我错过了什么?
我如何将 getAuth 和 onAuthStateChanged 方法与此依赖项一起使用?
感谢

Firebase.js 的建议:

// import "firebase/auth"
import "firebase/compat/auth"
//import {getAuth} from "firebase/firebase-auth";
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';

import { getAuth, onAuthStateChanged } from "firebase/auth";


// onAuthStateChanged(auth, user => {
//     // Check for user status
// });

const app = firebase.initializeApp({
    apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGIN_SENDER_ID,
    appId: process.env.REACT_APP_FIREBASE_APP_ID
})


export const auth = getAuth(app);

export default app

标签: javascriptreactjsfirebasefirebase-authentication

解决方案


import React, { useState } from 'react'
import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged, GoogleAuthProvider, signInWithPopup, signOut } from "firebase/auth";
import './App.css';

// import { getAnalytics } from "firebase/analytics";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

const firebaseConfig = {
  apiKey: 
  authDomain:
  databaseURL: 
  projectId: 
  storageBucket: 
  messagingSenderId: 
  appId: 
};


initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
const firebaseApp = initializeApp(firebaseConfig);
const provider = new GoogleAuthProvider();
const auth = getAuth(firebaseApp);

export default function App() {
  const [user, setUser] = useState(null)
  onAuthStateChanged(auth, (user) => {
          if (user) {
            // User is signed in, see docs for a list of available properties
            // https://firebase.google.com/docs/reference/js/firebase.User
            setUser(user);
            // ...
          } else {
            // User is signed out
            // ...
            setUser(null)
            }
          }
        );

  return <>{user ? 
  <><p>Welcome</p><button onClick={() => signOut(auth)}>Google Logout</button></>
  : <><p>Enjoy</p>
  <button onClick={() =>  signInWithPopup(auth, provider)
                  .then((result) => {
                    // The signed-in user info.
                    // eslint-disable-next-line
                    const user = result.user;
                    // ...
                  }).catch((error) => {
                    // Handle Errors here.
                    // eslint-disable-next-line
                    const errorCode = error.code;
                    // eslint-disable-next-line
                    const errorMessage = error.message;
                    // The email of the user's account used.
                    // eslint-disable-next-line
                    const email = error.email;
                    // The AuthCredential type that was used.
                    // eslint-disable-next-line
                    const credential = GoogleAuthProvider.credentialFromError(error);
                    // ...
                  })}>
                      Sign in with Google
                    </button>
  </>}</>
}

推荐阅读