You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件集成Firebase时出现No Firebase App错误的解决方法

修复Firebase未初始化的错误

错误原因

你遇到的Firebase: No Firebase App '[DEFAULT]' has been created错误,核心问题有两个:

  1. Firebase初始化时机错误:你在组件的render方法里调用firebase.initializeApp(),但render会多次执行,且在组件渲染前就已经执行了const auth = firebase.auth(),此时Firebase还未完成初始化,直接触发错误。
  2. 类组件state初始化位置错误:类组件的state应当在constructor中初始化,而非render方法内。

修复步骤

  1. 将Firebase初始化移到组件外部,全局仅执行一次:确保在调用任何Firebase功能前完成初始化,同时通过firebase.apps.length判断是否已初始化,避免重复执行初始化代码。
  2. 在类组件的constructor中初始化state:遵循React类组件的规范写法。
  3. 移除未使用的Hooks导入:类组件无法使用React Hooks,当前代码未用到的useAuthState、useCollectionData等可以先移除。

修复后的代码

import React, { Component } from 'react'
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/analytics';

// 全局初始化Firebase,仅执行一次
if (!firebase.apps.length) {
  firebase.initializeApp({
    apiKey: "xxxxxxxxxx",
    authDomain: "sssdsdsd.firapp.com",
    databaseURL: "https://xx-xx-default-rtdb.fireio.com",
    projectId: "xxx-d7287",
    storageBucket: "xxx-d7287.appspot.com",
    messagingSenderId: "xxxx",
    appId: "1:xxx:web:xxxx",
    measurementId: "G-xxxx"
  })
}

const auth = firebase.auth();
const firestore = firebase.firestore();

class InfoLgn extends Component {
  constructor(props) {
    super(props);
    // 在constructor中初始化state
    this.state = {
      user: null
    }
  }

  render() {
    return (
      <div>
         <div className="App">
        <header>
          <h1>⚛️🔥💬</h1>
          <SignOut />
        </header>
       </div>
      </div>
    )
  }
}

function SignOut() {
  return auth.currentUser && (
    <button className="sign-out" onClick={() => auth.signOut()}>Sign Out</button>
  )
}

export default InfoLgn

额外说明

如果后续需要在类组件中监听用户登录状态,可以使用Firebase的auth.onAuthStateChanged方法,在componentDidMount中注册监听,componentWillUnmount中取消监听,不要使用React Hooks(Hooks仅支持函数组件)。

内容的提问来源于stack exchange,提问作者BRDroid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:05:32