【问题标题】:firebase is not connected to Reactjsfirebase 未连接到 Reactjs
【发布时间】:2022-10-12 23:10:01
【问题描述】:

我在 reactjs 中建立了一个项目,它需要身份验证,所以我试图将它连接到 firebase,因为它是更简单的方法

我一直在关注 youtube 上的教程,但他的方式对我不起作用

这是我的代码:

firebase 配置代码:

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

// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "AIzaSyBoKEW_g0gOwNKkHGMAyhXxC0ESfdsVhKI",
  authDomain: "kargoevi-auth.firebaseapp.com",
  projectId: "kargoevi-auth",
  storageBucket: "kargoevi-auth.appspot.com",
  messagingSenderId: "726037811463",
  appId: "1:726037811463:web:42d75c7f5c1d1b5b9bf5a2",
  measurementId: "G-PJXGLVZ6GQ",
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

export default app;

授权码:

import React, { useState, useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "./base.js";

export const AuthContext = React.createContext();

export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [pending, setPending] = useState(true);

  useEffect(() => {
    onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
      setPending(false);
    });
  }, []);
  if (pending) {
    return <>Loading...</>;
  }

  return (
    <AuthContext.Provider
      value={{
        currentUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

私人路线代码:

import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import { AuthContext } from "./Auth";

const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
  const { currentUser } = useContext(AuthContext);
  return (
    <Route
      {...rest}
      render={(routeProps) =>
        !!currentUser ? (
          <RouteComponent {...routeProps} />
        ) : (
          <Redirect to={"/login"} />
        )
      }
    />
  );
};

export default PrivateRoute;

所以我的目标是在注册和登录时进行身份验证

这是注册和登录的代码

注册码:

import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth } from "../auth/base.js";

const SignUp = ({ history }) => {
  const handleSignUp = useCallback(
    async (event) => {
      event.preventDefault();
      const { email, password } = event.target.elements;
      try {
        await createUserWithEmailAndPassword(auth, email.value, password.Value);
        console.log("test");
        history.Push("/");
      } catch (error) {
        alert(error);
      }
    },
    [history]
  );

 return (
         <form
         onSubmit={handleSignUp}

      >

所以我想看看有人在firebase数据库中注册的时间 我也希望只有注册的人才能登录 现在它不起作用

【问题讨论】:

    标签: javascript reactjs authentication firebase-authentication


    【解决方案1】:

    您要导出的appFirebaseApp 的一个实例,并且没有.auth() 方法。您似乎正在关注使用旧命名空间版本的 Firebase SDK 的旧教程。而是尝试删除兼容库并重构代码,如下所示:

    import { initializeApp } from "firebase/app";
    import { getAuth, onAuthStateChanged } from "firebase/auth"; 
    
    const firebaseConfig = {...};
    
    const app = initializeApp(firebaseConfig);
    
    // use this auth instance else where
    export const auth = getAuth(app);
    

    在新的modular SDK 中,createUserWithEmailAndPassword() 是顶级函数。尝试:

    import { auth } from "../path/to/base.js"
    import { createUserWithEmailAndPassword } from "firebase/auth"
    
    const handleSignUp = useCallback(
      async (event) => {
          event.preventDefault();
          const { email, password } = event.target.elements;
          try {
            await createUserWithEmailAndPassword(auth, email.value, password.Value);
            history.Push("/");
          } catch (error) {
            alert(error);
          }
        },
        [history]
    );
    

    也结帐Getting started with Firebase Authentication on the web

    【讨论】:

    • 我不需要在配置中导出应用程序吗?
    • @Dharamaraj 也是同样的登录方法吗?
    • @HazalKaya 您通常不会,并且对于登录,有一个称为 signInWithEmailAndPassword() 的不同功能。请参考链接的视频。
    • 好的,我从昨天开始就在尝试,但是它不起作用,请您通过添加登录名来编辑您的答案吗?
    • @HazalKaya “登录”听起来像是一个完全不同的问题,我们甚至不知道您尝试了什么或遇到了什么错误。如果它与原始问题完全无关,最好发布一个新问题并将其标记为已回答,或者至少用更多详细信息更新当前问题。
    猜你喜欢
    • 2018-06-13
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    相关资源
    最近更新 更多