从 firebase 导入身份验证后,React 应用程序将不会渲染

问题描述 投票:0回答:1

Vite、React 和 Tailwind。 当我在导入了 firebase 的身份验证的浏览器上运行我的项目时,我的应用程序无法加载。现在,我意识到,当我将

import auth from 'firebase/auth'
放在代码末尾时,应用程序仍然会加载。因此,我假设导入需要更多时间,并且解决方案与异步导入相关。唉,我仍然没有找到正确的代码来修复它。

这是我的代码:

firebase.jsx

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import { getAuth } from "firebase/auth";

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "####",
  authDomain: "####.firebaseapp.com",
  projectId: "###",
  storageBucket: "###",
  messagingSenderId: "####",
  appId: "####",
  measurementId: "####"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const auth = getAuth();

SignUp.jsx

这是我想要让注册功能发挥作用的地方。因此,当输入第一行时,应用程序将崩溃。但是,当它放在最后一行代码时,它就不会了。如果导入在最后一行,我将无法正确编写代码。

import auth from '../firebase/firebase'
export default function SignUp(){
    return (
        <div className="rounded-xl w-2/5 flex-1 absolute h-2/4 bg-dark items-center left-2/4 top-2/4 -translate-y-2/4 -translate-x-2/4 ">
            <form action="">
                <h2 className="text-white text-3xl flex-1 font-mono font-bold text-center">Sign Up</h2>
                <input type="text" /> 
            </form>
        </div>
    )
}

我尝试使用在 stackexchange 上找到的语法进行异步导入,但它不起作用。

(async () => {

  const { getAuth } = await import('firebase/auth');

})();

我还尝试将

import { getAuth } from "firebase/auth";
放在注册文件上并从那里继续一切操作,但仍然不起作用。

javascript reactjs firebase vite
1个回答
0
投票

发生这种情况是因为 Firebase 的“getAnalytics()”依赖于可能无法立即使用的浏览器 API,特别是如果您没有在完整的浏览器环境(例如开发服务器)中运行。在“firebase.jsx”中,删除或有条件地加载分析服务,因为它是可选的。确保正确导入和导出身份验证。最后,导入“auth”。

© www.soinside.com 2019 - 2024. All rights reserved.