TypeError: null не является объектом - PullRequest
0 голосов
/ 18 марта 2020

Receiving TypeError: null не является объектом (оценивается как'_firebase $ auth $ currency.email ')

после успешного входа в Google я создал кнопку для перехода на следующий экран (главный экран). Я не выяснил, как сделать этот переход без появления этой ошибки.

, начиная с создания приложений с реагировать на родной .. эта ошибка появляется на IOS, я все еще пытаюсь отработать вход в Google для android, так что это появляется только на IOS.

экран входа

import React from 'react';
import { View, Text, StyleSheet, Alert, TextInput, ActivityIndicator, TouchableOpacity, 
Image, StatusBar, LayoutAnimation, ImageBackground, ScrollView, SafeAreaView, Dimensions } 
from 'react-native';
import * as firebase from 'firebase'
import { GoogleSignin, statusCodes, GoogleSigninButton } from '@react-native- 
community/google-signin';

const { height } = Dimensions.get('window');

export default class LoginScreen extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        userInfo: null,
        gettingLoginStatus: true,
    }
}
state = {
    // We don't know the size of the content initially, and the probably won't instantly try to scroll, so set the initial content height to 0
    screenHeight: 0,
};
onContentSizeChange = (contentWidth, contentHeight) => {
    // Save the content height in state
    this.setState({ screenHeight: contentHeight });
};
static navigationOptions = {
    headerShown: false
};
state = {
    email: "",
    password: "",
    errorMessage: null

};

handleLogin = () => {
    const { email, password } = this.state;

    firebase
        .auth()
        .signInWithEmailAndPassword(email, password)
        .catch(error => this.setState({ errorMessage: error.message }));
};

componentDidMount() {
    //initial configuration
    GoogleSignin.configure({
        //It is mandatory to call this method before attempting to call signIn()
        scopes: ['https://www.googleapis.com/auth/drive.readonly'],
        // Repleace with your webClientId generated from Firebase console
        webClientId: '734413363397-2p3pcf87ibhcnli6b4mtnqrbg3ntug9n.apps.googleusercontent.com', // client ID of type WEB for your server (needed to verify user ID and offline access)
    });
    //Check if user is already signed in
    this._isSignedIn();
}
_isSignedIn = async () => {
    const isSignedIn = await GoogleSignin.isSignedIn();
    if (isSignedIn) {
        alert('El usuario ya ha iniciado sesión');
        //Get the User details as user is already signed in
        this._getCurrentUserInfo();
    } else {
        //alert("Please Login");
        console.log('Please Login');
    }
    this.setState({ gettingLoginStatus: false });
};

_getCurrentUserInfo = async () => {
    try {
        const userInfo = await GoogleSignin.signInSilently();
        console.log('User Info --> ', userInfo);
        this.setState({ userInfo: userInfo });
    } catch (error) {
        if (error.code === statusCodes.SIGN_IN_REQUIRED) {
            alert('User has not signed in yet');
            console.log('User has not signed in yet');
        } else {
            alert("Something went wrong. Unable to get user's info");
            console.log("Something went wrong. Unable to get user's info");
        }
    }
};

_signIn = async () => {
    //Prompts a modal to let the user sign in into your application.
    try {
        await GoogleSignin.hasPlayServices({
            //Check if device has Google Play Services installed.
            //Always resolves to true on iOS.
            showPlayServicesUpdateDialog: true,
        });
        const userInfo = await GoogleSignin.signIn();
        console.log('User Info --> ', userInfo);
        this.setState({ userInfo: userInfo });
    } catch (error) {
        console.log('Message', error.message);
        if (error.code === statusCodes.SIGN_IN_CANCELLED) {
            console.log('User Cancelled the Login Flow');
        } else if (error.code === statusCodes.IN_PROGRESS) {
            console.log('Signing In');
        } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            console.log('Play Services Not Available or Outdated');
        } else {
            console.log('Some Other Error Happened');
        }
    }
};

_signOut = async () => {
    //Remove user session from the device.
    try {
        await GoogleSignin.revokeAccess();
        await GoogleSignin.signOut();
        this.setState({ userInfo: null }); // Remove the user from your app's state as well
    } catch (error) {
        console.error(error);
    }
};


render() {
    LayoutAnimation.easeInEaseOut();
    const scrollEnabled = this.state.screenHeight > height;
    if (this.state.gettingLoginStatus) {
        return (
            <View style={styles.container}>
                <ActivityIndicator size="large" color="#0000ff" />
            </View>
        );

    } else {
        if (this.state.userInfo != null) {
            //Showing the User detail
            return (

                <View style={styles.containerMain}>
                    <StatusBar barStyle="light-content"></StatusBar>
                    <ScrollView
                        style={{ flex: 1 }}
                        contentContainerStyle={styles.scrollview}
                        scrollEnabled={scrollEnabled}
                        onContentSizeChange={this.onContentSizeChange}
                    >
                        <ImageBackground source={require("/Users/carloscraig/NoExcusasRN/screens/assets/grassbcg2.png")}
                            style={{ width: '100%', height: '100%' }}>
                            <Image source={require("/Users/carloscraig/NoExcusasRN/screens/assets/noexlogo.png")}
                                style={styles.logo}>
                            </Image>


                            <Text style={styles.greeting}>{'BIENVENIDO!'}</Text>

                            <View style={styles.googlePhotoContainer}>
                                <Image
                                    source={{ uri: this.state.userInfo.user.photo }}
                                    style={styles.imageStyle}
                                />
                                <Text style={styles.text}>
                                   {this.state.userInfo.user.name}{' '}
                                </Text>
                                <Text style={styles.text}>
                                   {this.state.userInfo.user.email}
                                </Text>
                                <TouchableOpacity
                                style={{ alignSelf: "center", marginTop: 32 }}
                                onPress={() => this.props.navigation.navigate("Home")}
                            >
                                <Text style={ styles.textsmall }>
                                    Entrar la aplicación <Text style={{ fontWeight: "800", color: "#E9446A" }}>Aqui</Text>
                                </Text>



                            </TouchableOpacity>
                                <TouchableOpacity style={styles.button2} onPress={this._signOut}>
                                    <Text>Cerrar Sesión</Text>
                                </TouchableOpacity>
                            </View>






                            </ImageBackground>
                    </ScrollView>
                </View>
                );



} else {
            LayoutAnimation.easeInEaseOut();
            const scrollEnabled = this.state.screenHeight > height;
            //For login showing the Signin button
            return (
                <View style={styles.containerMain}>
                    <StatusBar barStyle="light-content"></StatusBar>
                    <ScrollView
                        style={{ flex: 1 }}
                        contentContainerStyle={styles.scrollview}
                        scrollEnabled={scrollEnabled}
                        onContentSizeChange={this.onContentSizeChange}
                    >
                        <ImageBackground source={require("/Users/carloscraig/NoExcusasRN/screens/assets/grassbcg2.png")}
                            style={{ width: '100%', height: '100%' }}>
                            <Image source={require("/Users/carloscraig/NoExcusasRN/screens/assets/noexlogo.png")}
                                style={styles.logo}>
                            </Image>


                            <Text style={styles.greeting}>{'BIENVENIDO!'}</Text>

                            <View style={styles.errorMessage}>
                                {this.state.errorMessage && <Text style={styles.error}>{this.state.errorMessage}</Text>}
                            </View>

                            <View style={styles.form}>
                                <View>
                                    <Text style={styles.inputTitle}>correo electrónico</Text>
                                    <TextInput
                                        style={styles.input}
                                        autoCapitalize="none"
                                        onChangeText={email => this.setState({ email })}
                                        value={this.state.email}
                                    ></TextInput>
                                </View>

                                <View style={{ marginTop: 32 }}>
                                    <Text style={styles.inputTitle}>contraseña</Text>
                                    <TextInput
                                        style={styles.input}
                                        secureTextEntry
                                        autoCapitalize="none"
                                        onChangeText={password => this.setState({ password })}
                                        value={this.state.password}
                                    ></TextInput>
                                </View>
                            </View>

                            <TouchableOpacity style={styles.button} onPress={this.handleLogin}>
                                <Text style={{ color: "#FFF", fontWeight: "500" }}>Iniciar Sesión</Text>
                            </TouchableOpacity>

                <View style={styles.buttonGoogle}>
                    <GoogleSigninButton
                       style={styles.buttonGoogle}
                        size={GoogleSigninButton.Size.Wide}
                        color={GoogleSigninButton.Color.Light}
                        onPress={this._signIn}
                    />
                </View>

                <TouchableOpacity
                                style={{ alignSelf: "center", marginTop: 20 }}
                                onPress={() => this.props.navigation.navigate("Register")}
                            >
                                <Text style={ styles.textsmall }>
                                    No tienes una Cuenta? <Text style={{ fontWeight: "500", color: "#E9446A" }}>Regístrate</Text>
                                </Text>



                            </TouchableOpacity>

                </ImageBackground>
                    </ScrollView>
                </View>
            );
        };
    }
}
}

код для главного экрана

import React from 'react'
import{View, Text, StyleSheet,TouchableOpacity} from 'react-native'
 import * as firebase from 'firebase'

 export default class HomeScreen extends React.Component {
state = {
    email: "",
    displayName: ""
};

componentDidMount() {
    const { email, displayName } = firebase.auth().currentUser;

    this.setState({ email, displayName });
}

signOutUser = () => {
    firebase.auth().signOut();
};

render (){
    return(
        <View style={styles.container}>
            <Text>Hi {this.state.email}!</Text>

            <TouchableOpacity style={{marginTop:32 }} onPress={this.signOutUser}>
                <Text>Logout</Text>
            </TouchableOpacity>
        </View>
    );
}
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...