【问题标题】:React Firebase Auth initialization problem - No Firebase App '[DEFAULT]' has been createdReact Firebase Auth 初始化问题 - 没有创建 Firebase App '[DEFAULT]'
【发布时间】:2021-03-14 07:08:57
【问题描述】:

功能:如果他或她在之前的网络会话中成功登录,我想使用用户的个人资料自动登录。

问题:我在尝试执行 firebase.auth() 时在我的 React 项目中收到“No Firebase App”错误。主要的 firebase 对象初始化在我的 index.js 文件的末尾触发,firebase.initializeApp(firebaseConfig)。据我所知,firebase 实例在执行代码的身份验证部分时未正确初始化。通常,我希望对 init 函数的回调执行身份验证,但没有。所以我的问题是在网页加载期间进行上述自动身份验证/登录的最佳位置是什么?目前验证是在componentDidMount 上执行的,这显然不能解决问题......

  componentDidMount = () => {
    if (localStorage.getItem("auth") == "google")
      this.authenticate();
  };
  authenticate = () => {
    var provider = new firebase.auth.GoogleAuthProvider();

    firebase // <- exception
      .auth() 
      .signInWithPopup(provider)
      .then(function (result) {
        // @ts-ignore
        var token = result.credential.accessToken;
        user = result.user;
        localStorage.setItem("auth", "google");

【问题讨论】:

  • 您是否尝试将 firebase.initializeApp(firebaseConfig) 放在 index.js 的开头,在组件之前而不是结尾?
  • 是的,我已经尝试过了(在ReactDOM.render 部分代码之前),但出现以下错误:未处理的拒绝(TransactionInactiveError):针对当前未激活或已完成的事务发出请求

标签: reactjs firebase firebase-authentication


【解决方案1】:

在 index.html 的正文中添加:

<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>

  <!-- Add analytics if you need them -->
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-analytics.js"></script>

  <!--Add firebase dependencies you need (here i added auth and firestore) -->
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-firestore.js"></script>
  
   <script>
    // TODO: Replace the following with your app's Firebase project configuration
    // For Firebase JavaScript SDK v7.20.0 and later, `measurementId` is an optional field
    var firebaseConfig = {
      // ... You can find config in settings, scroll down and click on cdn
      // I use cdn since it allows both external and firebase hosting
    };

    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  </script>

那你准备好了

【讨论】:

  • 如果您需要找到其他库,这里是cdn的参考:firebase.google.com/docs/web/setup?authuser=0#expandable-8
  • 是的,我也已经尝试过了,但没有运气。也没有理由添加 Firestore,因为我没有利用它
  • 好吧,就像我说的那样,这是一个例子。如果我发现了什么我会更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2021-07-13
  • 2021-06-12
  • 2018-11-21
  • 2021-07-25
  • 2020-05-21
相关资源
最近更新 更多