Получение ошибки «неопределенный не является объектом (оценка ‘navigation.navigate’)» после аутентификации firebase — react native

#javascript #firebase #react-native

#javascript #firebase #react-native

Вопрос:

Привет, я получаю сообщение об ошибке undefined не является объектом (оценка ‘navigation.navigate’) после отправки формы. Я искал много ответов Google / stackoverflow, но ни один из них мне не помог.

Я не уверен, вызвано ли это firebase или фактической навигацией. Есть идеи по этому поводу???

Пожалуйста, посмотрите код ниже:

 // parent component

import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import LoginForm from '../components/LoginForm';

const Login = () => {
    return (
        <View style={styles.mainWrapper}>
            <Image style={styles.logo} title="Logo" source={require('../assets/box.png')}/>
            <LoginForm/>
        </View>
    );
}

const styles = StyleSheet.create({
    logo: {
        width: 150,
        height: 150,
        marginTop: 55
    },
    mainWrapper: {
        display: "flex",
        alignItems: "center"
    }
});

export default Login;






// login form component

import React, { useState } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity, Alert} from 'react-native';
import firebase from 'firebase/app';
import 'firebase/auth';
import { firebaseConfig } from '../config';

if(!firebase.apps.length){
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
}

const auth = firebase.auth();

const LoginForm = ({navigation}) => {

    const [email,setEmail] = useState('');
    const [password, setPassword] = useState('');

    const signIn = async() => {
        try {
            let response = await auth.signInWithEmailAndPassword(email,password);
            if(response.user){
                Alert.alert('logged in'   response.user.email);
                navigation.navigate('Driver');
            }
        }catch(e){
            Alert.alert(e.message);
        }
    };

    return (
        <View style={styles.formView}>
            <TextInput
            value={email}
            placeholder="Email" 
            style={styles.input}
            onChangeText={userEmail => setEmail(userEmail)}
            autoCapitalize='none'
            keyboardType='email-address'
            autoCorrect={false}
            />

            <TextInput 
            value={password}
            placeholder="Password" 
            secureTextEntry={true} 
            style={styles.input}
            onChangeText={userPassword => setPassword(userPassword)}
            />

            <TouchableOpacity style={styles.submitBtn} title="Login" onPress={() => signIn()}>
                <Text style={styles.appButtonText}>Login</Text>
            </TouchableOpacity>
        </View>
    );
}

const styles = StyleSheet.create({
    formView: {
        marginTop: 45,
        display: "flex",
        alignItems: "center",
    },
    input: {
        marginTop: 20,
        width: 300,
        height: 40,
        paddingHorizontal: 10,
        borderRadius: 5,
        backgroundColor: 'white',
    },
    submitBtn: {
        backgroundColor: "#FFE17D",
        color: "#E6646E",
        fontWeight: "bold",
        width: 150,
        height: 40,
        marginTop: 20,
        borderColor: "#E6646E",
        borderRadius: 5,
        display: "flex",
        justifyContent: "center",
        borderWidth: 1,
    },
    appButtonText: {
      fontSize: 18,
      color: "#E6646E",
      fontWeight: "bold",
      alignSelf: "center",
      textTransform: "uppercase"
    }
});  

Комментарии:

1. Пожалуйста, поделитесь также родительским компонентом, чтобы мы не играли в догадки о том, что такое props.navigation

2. Является ли компонент входа в систему частью стека? здесь нет кода, связанного с навигацией, и вы также не передаете навигационный реквизит в LoginForm

3. Компонент входа в систему не является частью стека

4. Если он не является частью стека, вам следует использовать ссылку для проверки api reactnavigation.org/docs/navigating-without-navigation-prop

Ответ №1:

Только экраны стека имеют доступ к навигации по реквизитам. Вы можете попробовать отправить навигацию в LoginForm, но это работает, только если Login — это экран стека.

 const Login = ({navigation}) => {
    return (
        <View style={styles.mainWrapper}>
            <Image style={styles.logo} title="Logo" source={require('../assets/box.png')}/>
            <LoginForm navigation={navigation}/>
        </View>
    );
}
  

Или вы можете взглянуть на хук useNavigation