如何使用firebase.auth而不在我的帐户文件中再次初始化firebase

时间:2019-03-12 01:59:16

标签: javascript reactjs firebase react-native react-redux

我收到此错误,因为在我的account.js文件中再次初始化了Firebase。我想使用firebase.auth,所以我的account.js文件在注销时将显示登录表单,在登录时将显示注销按钮。是否有正确的方法? enter image description here

Account.js

import React from 'react';
import firebase from 'firebase';
import { View, Image, TouchableOpacity, Text, TextInput } from 'react-native';
import { StackNavigator, TabNavigator } from 'react-navigation';
import { Card, Button, Spinner, CardSection } from '../common';
import LoginForm from '../LoginForm';
import router from '../../config/router';

class Account extends React.Component {
  state = { loggedIn: false };

  componentWillMount() {
    firebase.initializeApp({
    apiKey: 'sksssk',
    authDomain: 'ssjkjskjs',
    databaseURL: 'skhskjhsk',
    projectId: 'sijisj',
    messagingSenderId: 'jwuduwid'
  });
  firebase.auth().onAuthStateChanged((user) => {
    //event handler that handles either signing in or signing out
    if (user) {
      this.setState({ loggedIn: true });
    } else {
      this.setState({ loggedIn: false });
    }
  });
    }
    renderContent() {
      if (this.state.loggedIn) {
        return (
          <Provider store={store}>
            <Tabs />
            <Button>
              Log Out
            </Button>
          </Provider>
        );
      }

App.js

class App extends Component {
  state = { loggedIn: false };

  //lifecyle method for firebase initialization
  componentWillMount() {
    firebase.initializeApp({
        apiKey: 'sksssk',
        authDomain: 'ssjkjskjs',
        databaseURL: 'skhskjhsk',
        projectId: 'sijisj',
        messagingSenderId: 'jwuduwid'
  });
firebase.auth().onAuthStateChanged((user) => {
  //event handler that handles either signing in or signing out
  if (user) {
    this.setState({ loggedIn: true });
  } else {
    this.setState({ loggedIn: false });
  }
});
  }
  renderContent() {
    if (this.state.loggedIn) {
      return (
        <Provider store={store}>
          <Tabs />
        </Provider>
      );
    }
  }

  render() {
    return (
      <Provider store={store}>
        <Tabs />
      </Provider>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

最好的方法是确保初始化在一个只能执行一次的地方,正如亚历山大所说。

或者,有时我只是检测Firebase是否已经初始化:

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

请注意,如果您在应用中使用多个FirebaseApp实例,则以上代码段将无效。