为什么 Firebase 无法识别我的 Firebase 实例? "call Firebase App.intializeApp()"



我有两个文件,一个App.js我在其中设置了我的 React Navigation StackNavigator 以及我的 firebase 实例,另一个是我登录用户的Login.js

我正在尝试检测用户是否已经登录(通过 firebase 持久登录(,但由于某种原因,我的 firebase 实例在Login.jscomponentDidMount()中未被检测到。这对我来说没有意义,因为在我Login.js的其他地方,我在 firebase 实例上调用 fxns,就像使用 Google 登录一样。

我应该如何安排 Firebase 初始化/身份验证检查,以确保正确检测到 Firebase 实例以及持久身份验证检查?

我已经看过这个问题,但那个人似乎有不同的问题,因为他们只关心单个文件中的 firebase 实例。

App.js的相关部分

import { StackNavigator } from 'react-navigation';
import * as firebase from 'firebase';
import 'firebase/firestore';
import Login from './components/login';
const Application = StackNavigator({
Login: { screen: Login,
navigationOptions: {
title: 'Login',
}
},
SignUp: { screen: SignUp,
navigationOptions: {
title: 'Signup',
}
},
Home: { screen: Home,
navigationOptions: {
title: 'Home'
}
},
});
const firebaseConfig = {
apiKey: "APIKEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DATABASE_URL",
projectId: "PROJECT_ID",
storageBucket: "BUCKET",
}
export default class App extends React.Component {
componentDidMount(){
//if no instance exists, initialize one
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
}
render() {
return (
<Application/>
);
}
}

Login.js的相关部分

import * as firebase from 'firebase';
import Home from './home';
export default class Login extends React.Component {
constructor(props){
super(props)
this.state = {
isLoggingIn: true,
authFlag: false,
}
}
componentDidMount() {
//error is on the following line
firebase.auth().onAuthStateChanged((user) => {
if(!this.state.authFlag){
this.setState({ authFlag: true })
//persistent success, take user to Home
if(user){
this.props.navigation.navigate('Home');
return;
}
//user hasn't logged in before, must log in
else{
this.setState({isLoggingIn: false});
return;
}
}
});
}
}

正如我在上面的评论中提到的,子组件先于它们的父组件安装。componentDidMount登录组件在componentDidMount应用之前发生。堆栈溢出问题概述了 deet。

只需快速搜索一下,看起来大多数人都在他们的组件之外做firebase.initializeApp。只是在读这个。

最新更新