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

Firebase+React官方教程代码报错求助:两种组件写法均编译失败

Fixing Your React + Firebase App Compilation Errors

Hey there! Let's walk through fixing the two main issues in your code—since you're new to React and Firebase, we'll keep this simple and straightforward.


1. First Error: Using constructor in a Function Component

Your initial code was a function component (defined with function App() { ... }), but you tried to add a constructor—this is only valid for class components. Function components can't use this.state or constructor directly (you'd use the useState hook instead if you wanted to stick with function components).


2. Second Error: Typo in Class Component Declaration

When you switched to a class component, you made a small but critical typo: extend should be extends (missing an "s"). This syntax mistake breaks the entire class definition, causing the compiler to throw an error.


Correct Working Code

Here's the fixed version of your class component, with key details explained:

// Import React and Component (required for class-based components)
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import * as firebase from 'firebase';

// Correct class declaration with "extends" (not "extend")
class App extends Component {
  // Constructor for initializing state and binding methods
  constructor() {
    super(); // Must call super() first in a class component constructor
    // Initialize component state with your speed value
    this.state = { speed: 10 };
  }

  // Render method to render your app's UI
  render() {
    return (
      <div className="App">
        <h1>{this.state.speed}</h1>
      </div>
    );
  }
}

export default App;

Quick Tip for Firebase Realtime Database

Since you're building an app to read from Firebase Realtime Database, don't forget to initialize Firebase in your project. Add this code (you can get your unique config from the Firebase Console) either in App.js or a separate firebase.js file:

// Firebase config (replace with your project's values from Firebase Console)
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  databaseURL: "YOUR_DATABASE_URL",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase only once to avoid duplicate app instances
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

Once initialized, you can use firebase.database().ref() to connect to your database and start reading data later on.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:18:08