React-native undefined 不是一个函数(评估 'firebase.auth()')



我正在开发带有firebase身份验证的本机应用程序作为电子邮件登录。较早的工作正常。但是它显示上述错误。我尝试了我所知道的一切。请帮助我修复它

import React from "react";
import {
Text,
View,
Image,
TouchableOpacity,
AsyncStorage,
TextInput,
KeyboardAvoidingView,
ScrollView,
ActivityIndicator
} from "react-native";
import { styles } from "./Css";
import * as firebase from "firebase";
//import firebase from '@firebase/app';
//require('firebase/auth');
//import firebase from 'firebase/app';
import 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import { GoogleSignin } from 'react-native-google-signin';
var asyncValue;
//const auth = firebase.auth();
export default class Login extends React.Component {
constructor(props) {
    super(props);
    this.state = {
    email: "",
    password: "",
    userId: "",
    errorMessage: null,
    animating: false,
    };
}
navigation1= this.props.navigation

componentDidMount() {
    this._loadInitialState().done();
    //Activity indicator
    //this.setToggleTimeout()
}
componentWillUnmount(){
    clearTimeout(this._timer)
}
_loadInitialState = async () => {
asyncValue = await AsyncStorage.getItem("user");
    //alert("value=" + value)
    if (asyncValue !== null) {
    //this.props.navigation.navigate('SuperMarket1')
    }
//=============SignIn With Google==============
GoogleSignin.configure({
    webClientId: 'clientid',
    //forceConsentPrompt: true, // if you want to show the authorization prompt at each login
});
//==============================================
};
setToggleTimeout(){
    this._timer = setTimeout(()=>{
    this.setState({ animating: !this.state.animating})
    this.setToggleTimeout()}, 2000)
}
///////////////////
navigate(routeName) {
    this.props.navigator.push({
        name: routeName
    });}
///////////////////
handleLogin = (email, password) => {
    if(this.state.email.length<1){
    alert("Enter an Email");
    return;
    }
    if (this.state.email.includes("@")==false){
        alert("Use an email as Username");
        return;
    }
    if(this.state.password.length<6){
    alert("please enter correct password")
    return;
    }
    console.log("uuid= " + firebase.auth().currentUser.uid)
    firebase.auth().signInWithEmailAndPassword(email, password).then((user) => {
    this.props.navigation.navigate('SuperMarket1')
    if(user){
        //--------------------------Async Test--------------------------
        AsyncStorage.setItem("user", firebase.auth().currentUser.uid)
        console.log("AsyncStorage= "+ asyncValue)
        //--------------------------------------------------------------
    }else{
    }
    }
    )
    .catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        if (errorCode === "auth/wrong-password") {
        alert("Wrong password.");
        return;
        } else {
        alert(errorMessage);
        return;
        }
        console.log(error);
    });
    // //--------------------------Async Test--------------------------
    // AsyncStorage.setItem("user", firebase.auth().currentUser.uid);
    // //--------------------------------------------------------------
};
//-------------------------------Temp Functions-----------------
fb = () => {
    this.props.navigation.navigate("SuperMarket1");
    alert("Curently atuo logged in with Developers FB ID");
};
Glg = () => {
    console.log(firebase.auth) // Undefined
    console.log(firebase.default.auth) // Function
    GoogleSignin.hasPlayServices()
        .then(res => {
            GoogleSignin.signIn()
            .then(res => {
            console.log('res:'+res);
            const credential = firebase.auth.GoogleAuthProvider.credential(res.idToken, res.accessToken)
            console.log('res:'+credential);
            return firebase.auth().signInWithCredential(credential);
            })
            .catch(err => {
                console.log(error.code);
            });
        })
        .catch(err => {
            console.log(err);
        });
};
twt = () => {
    this.props.navigation.navigate("SuperMarket1");
    alert("Curently atuo logged in with Developers Twt ID");
};
//-------------------------------------------------------------
fgt = () => {
    this.props.navigation("ForgotPassword");
};
render() {
    return (
    <View style={styles.container}>
        <ActivityIndicator
        animating={this.state.animating}
        style={[styles.centering,{height:80}]}
        size="large"
    />
        <KeyboardAvoidingView style={styles.Top} behavior="padding" enabled>
    <Image
            style={styles.Image}
            source={require("../src/Assets/logo.png")}
        />
        </KeyboardAvoidingView>

        <View style={styles.Second}>
        <View style={styles.Third}>
            <Text style={styles.Textfirst}>Log In</Text>

        </View>
        <View style={styles.Fourth}>
            <View style={styles.Fifth}>
            <Image
                style={styles.Imagesecond}
                source={require("../src/Assets/Profile-xhdpi.png")}
            />
            </View>
            <View style={styles.Sixth}>
            <Text style={styles.Textsecond}>USER/EMAIL</Text>
            <TextInput 
                placeholder="user@mail.com                 " style={styles.one} underlineColorAndroid='transparent'
                //--------------value Handler----------------//
                onChangeText={email => this.setState({ email })}
                ////---------------------------------//
                keyboardType="email-address"
            />
            </View>
        </View>
        <View style={styles.Seventh}>
            <View style={styles.Eighth}>
            <Image
                style={styles.Imagethird}
                source={require("../src/Assets/8-layers-xhdpi.png")}
            />
            </View>
            <View style={styles.ninth}>
            <Text style={styles.Textsecond}>PASSWORD</Text>
            <TextInput style={styles.one} underlineColorAndroid='transparent'
                placeholder="**************                   "
                secureTextEntry={true}
                //--------------value Handler----------------//
                onChangeText={password => this.setState({ password })}
                //---------------------------------//
            />
            </View>
        </View>
        <View style={styles.Tenth}>
            <Text style={styles.Textfourth}>Forget password?</Text>
            <Text
            style={styles.Textfifth}
            onPress={() => this.props.navigation.navigate("ForgotPassword")}
            >
            {" "}
            Click here
            </Text>
        </View>

        <View style={styles.Eleventh}>
            {/* --------Login With Facebook-------- */}
        <TouchableOpacity onPress={()=>this.fb()}>
            <Image
            style={styles.Imagefourth}
            source={require("../src/Assets/3-layers-hdpi.png")}
            />
            </TouchableOpacity>
            {/* --------------------------------- */}
            {/* --------Login With Google-------- */}
            <TouchableOpacity onPress={()=>this.Glg()}>
            <Image
            style={styles.Imagefourth}
            source={require("../src/Assets/5-layers-hdpi.png")}
            />
            </TouchableOpacity>
            {/* --------------------------------- */}
            {/* --------Login With Twitter-------- */}
            <TouchableOpacity onPress={()=>this.twt()}>
            <Image
            style={styles.Imagefourth}
            source={require("../src/Assets/4-layers-xhdpi.png")}
            />
            </TouchableOpacity>
            {/* --------------------------------- */}
        </View>
        <TouchableOpacity style={styles.Twelth} onPress={()=>this.handleLogin(this.state.email,this.state.password)}>
            <View style={styles.Thirteenth}>
            <Text style={styles.Textsixth}>LOG IN</Text>
            </View>
            <View style={styles.Fourteenth}>
            <View style={styles.Fifteenth}>
                <Image
                style={styles.Imagefifth}
                source={require("../src/Assets/Path_11.png")}
                />
            </View>
            </View>
        </TouchableOpacity>
        <View style={styles.Sixteenth}>
            <Text style={styles.Textseventh}>Dont have an account?</Text>
            <Text
            style={styles.Texteighth}
            onPress={() => this.props.navigation.navigate("SignUp")}
            >
            Create a new account
            </Text>
        </View>
        </View>
    </View>
    );
  }
}

这是我的app.js

import { View } from 'react-native';
import firebase from '@firebase/app';
import { Header } from './components/common';
import LoginForm from './components/LoginForm';
type Props = {};
export default class App extends Component<Props> {
  componentWillMount() {
    firebase.initializeApp({
      apiKey: 'AIzaSyAq4eGitgRxVzu2CTRLtTygGflOb99CM0Q',
      authDomain: 'auth-62da8.firebaseapp.com',
      databaseURL: 'https://auth-62da8.firebaseio.com',
      projectId: 'auth-62da8',
      storageBucket: 'auth-62da8.appspot.com',
      messagingSenderId: '851651021407'
    });
  }
  render() {
    return (
      <View>
        <Header headerText='Authentication' />
        <LoginForm />
      </View>
    );
  }
}

这是我的登录名

import React, { Component } from 'react';
import { Text } from 'react-native';
import firebase from '@firebase/app';
import { Button, Card, CardSection, Field, Spinner } from './common';
require('@firebase/auth');
class LoginForm extends Component {
  state = { email: '', password: '', error: '', loading: false };
  onButtonPress() {
    this.setState({ error: '', loading: true });
    firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
      .then(this.onLoginSuccess.bind(this))
      .catch(() => {
        firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
          .then(this.onLoginSuccess.bind(this))
          .catch(this.onLoginFail.bind(this));
      });
  }
  onLoginFail() {
    this.setState({
      loading: false,
      error: 'Authentication Failed'
    });
  }
  onLoginSuccess() {
    this.setState({
      email: '',
      password: '',
      loading: false,
      error: ''
    });
  }
  renderButton() {
    if (this.state.loading) {
      return <Spinner size='small' />;
    }
    return (
      <Button onPress={this.onButtonPress.bind(this)}>
        Login
      </Button>
    );
  }
  render() {
    return (
      <Card>
        <CardSection>
          <Field
            labelText={'Email'}
            placeholder={'email'}
            value={this.state.email}
            onChangeText={email => this.setState({ email })}
          />
        </CardSection>
        <CardSection>
          <Field
            labelText={'Password'}
            placeholder={'password'}
            hideInput
            value={this.state.password}
            onChangeText={password => this.setState({ password })}
          />
        </CardSection>
        <Text style={styles.errorTextStyle}>
          {this.state.error}
        </Text>
        <CardSection>
          {this.renderButton()}
        </CardSection>
      </Card>
    );
  }
}
const styles = {
  errorTextStyle: {
    fontSize: 20,
    alignSelf: 'center',
    color: 'red'
  }
};
export default LoginForm;

我与您遇到了完全相同的问题,这些是将其修复的导入/要求。我希望这会有所帮助!

相关内容

  • 没有找到相关文章

最新更新