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

React Hook useAuthState调用报错求助(Firebase聊天应用开发)

解决React Hook "useAuthState" 调用位置错误问题

错误原因

你遇到的ESLint错误和Node.js、Firebase版本兼容性无关,核心问题是违反了React Hooks的使用规则:React Hooks必须在React函数组件或自定义Hook的顶层调用,不能在组件外部的全局作用域执行。你的代码中useAuthState被写在了App组件之外,这不符合规则。

修复方案

将useAuthState的调用移到App组件内部,同时修正代码中组件名称拼写不一致的问题(Chatroom → ChatRoom),修改后的完整代码如下:

import React from 'react'
import './App.css';

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

import {useAuthState} from 'react-firebase-hooks/auth';
import {useCollectionData} from 'react-firebase-hooks/firestore';

firebase.initializeApp({
  apiKey: "AIzaCpaZUFe6R2B-l_sTcLLAVt8OlGQ",
  authDomain: "chatapp-9.firebaseapp.com",
  projectId: "chatapp-09",
  storageBucket: "chatapp-a78ppspot.com",
  messagingSenderId: "447574386",
  appId: "1:447083574386b65c8df29c31b067eeb",
  measurementId: "G-98NRKDY"
});

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

function App() {
  // 将useAuthState移到组件内部顶层
  const [user] = useAuthState(auth);

  return (
    <div className="App">
      <header className="App-header">
        <section>
          {/* 修正组件名称拼写:Chatroom → ChatRoom */}
          {user ? <ChatRoom /> : <SignIn />}
        </section>
      </header>
    </div>
  );
}

function SignIn() {
  const signInWithGoogle = () => {
    const provider = new firebase.auth.GoogleAuthProvider();
    auth.signInWithPopup(provider);
  }

  return (
    <button onClick={signInWithGoogle}>Sign in with Google</button>
  );
}

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

function ChatRoom() {}

export default App;

额外注意事项

  • 所有React Hooks必须在组件的顶层作用域调用,不能放在条件判断、循环、嵌套函数中,否则会导致组件状态异常。
  • 如果需要在多个组件中共享用户认证状态,可以封装自定义Hook,例如:
function useAuth() {
  const [user] = useAuthState(auth);
  return user;
}

这样其他组件可以直接调用useAuth()获取用户状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:15:49