如何在我的 React Native Expo 项目上设置 Firebase 分析?

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

我遵循了this文档,这看起来非常简单,但是我不断得到

error while setting analytics user id:  [Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()]

这是我的

App.js
文件的一部分:

import { auth } from './firebase.js'
import analytics from '@react-native-firebase/analytics';

const App = () => {
  
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    (async () => {
      if(currentUser){
        console.log("I have current user: ", analytics())
        try{
            await analytics().setUserId(currentUser.uid)
            console.log("all done")
        }catch(error){
          console.log("error while setting analytics user id: ", error);
        }
      }
    })();
  }, [currentUser]);

  useEffect(() => {
   const unsubscribe = auth.onAuthStateChanged((user) =>  {
        if (user) {
          setCurrentUser(user);
        }
    });
   return () => unsubscribe();
 }, []);


  if(!currentUser){
      return (
        <NavigationContainer>
          <AuthNavigator />
        </NavigationContainer>
      );
  }
  else{
    return (
        <NavigationContainer>
          <MainNavigator />
        </NavigationContainer>
    );
  }
};

export default App;

我的 firebase.js 文件:

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

const firebaseConfig = {
  apiKey: "some_key",
  authDomain: "some_domain",
  databaseURL: "some_url",
  projectId: "some_project_id",
  storageBucket: "some_id",
  messagingSenderId: "id",
  appId: "id",
  measurementId: "id"
};

if (firebase.apps.length === 0) {
  firebase.initializeApp(firebaseConfig);
}


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

有人可以帮忙吗,因为我在这个问题上花了太多时间。我正确地遵循了文档,我不明白为什么它会抱怨

[Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()]

请不要给我指出文档,我读了很多遍,我需要实用的解决方案。

javascript firebase firebase-analytics
1个回答
0
投票

您的 firebase.js 使用标准

firebase
包进行初始化,但您的 App.js 使用
@react-native-firebase
。 这些软件包彼此不兼容。 您无法使用
firebase
包初始化 Firebase 并使其与
@react-native-firebase
API 一起使用。

您说过您不想要文档链接,但我鼓励您重新考虑,就初始化 Firebase 而言,您可能阅读了错误的文档。 如果您使用

@react-native-firebase
进行分析,那么您应该使用正确的 文档 来初始化 Firebase。 该页面上有有关在 Expo 项目中初始化 Firebase 的说明。 我不会在这里复制任何内容,但听起来您只需要添加一些配置插件即可使其工作:

配置 React Native Firebase 的推荐方法是使用 Expo 配置插件。您将把 React Native Firebase 模块添加到 app.json 或 app.config.js 的插件数组中。请参阅下面的注释来确定哪些模块需要 Config Plugin 配置。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.