使用SolidJS与solid-firebase时遇Component auth未注册错误求助
问题
使用SolidJS搭配solid-firebase开发,直接复用官方仓库代码仅替换自身Firebase项目配置后,运行npm run dev访问localhost:3000/时页面空白,控制台报错:Component auth has not been registered yet。
App.tsx代码:
import type { Component } from 'solid-js' import { Match, Switch } from 'solid-js' import { GoogleAuthProvider, getAuth, signInWithPopup } from 'firebase/auth' import { useAuth, useFirebaseApp } from 'solid-firebase' const Login: Component = () => { const app = useFirebaseApp() const signIn = () => signInWithPopup(getAuth(app), new GoogleAuthProvider()) return <button onClick={signIn}>Sign In with Google</button> } const App: Component = () => { const app = useFirebaseApp() const state = useAuth(getAuth(app)) return ( <Switch> <Match when={state.loading}> <p>Loading...</p> </Match> <Match when={state.error}> <Login /> </Match> <Match when={state.data}> <h1>Logged In</h1> </Match> </Switch> ) } export default App
index.tsx(firebaseConfig已隐藏)代码:
import { render } from 'solid-js/web' import { FirebaseProvider } from 'solid-firebase' import './index.css' import App from './App' const root = document.getElementById('root')! const firebaseConfig = { apiKey: ..., authDomain: ..., projectId: ..., storageBucket: ..., messagingSenderId: ..., appId: ..., measurementId: ..., } if (import.meta.env.DEV && !(root instanceof HTMLElement)) { throw new Error( 'Root element not found. Did you forget to add it to your index.html? Or maybe the id attribute got mispelled?' ) } render( () => ( <FirebaseProvider config={firebaseConfig}> <App /> </FirebaseProvider> ), root )
解决方案
报错核心原因是Firebase Auth模块未被正确注册初始化,按以下步骤修复:
显式导入并注册Auth模块
在index.tsx中添加Auth模块的导入,确保Firebase能识别并加载Auth组件:import { render } from 'solid-js/web' import { FirebaseProvider } from 'solid-firebase' // 新增导入Auth模块 import 'firebase/auth' import { getAuth } from 'firebase/auth' import './index.css' import App from './App' // 其余代码保持不变简化Auth实例获取逻辑
solid-firebase的useAuth钩子会自动关联FirebaseProvider中的Auth实例,无需手动调用getAuth(app),修改App.tsx中的对应代码:const App: Component = () => { // 移除const app = useFirebaseApp() const state = useAuth() // 直接调用useAuth即可 return ( <Switch> {/* 其余JSX内容不变 */} </Switch> ) }验证Firebase配置正确性
确认firebaseConfig中的authDomain与Firebase控制台项目的Auth域名完全匹配,避免因配置错误导致Auth模块初始化失败。
内容的提问来源于stack exchange,提问作者HarryBilney
相关产品推荐
相关产品推荐

