导航问题本机反应

时间:2020-11-10 11:03:45

标签: reactjs react-native react-navigation auth0

我在导航方面做错了,我使用SwitchNavigator处理身份验证和应用程序导航

执行登录后,我尝试将用户重定向到AppNavigation,但是我收到此错误消息:

未定义不是对象(正在评估“ this.props.navigation”)

Navigation.js

import { createSwitchNavigator, createAppContainer } from 'react-navigation'
import AuthNavigation from './AuthNavigation'
import AppNavigation from './AppNavigation'

const SwitchNavigator = createSwitchNavigator(
  {
    Auth: AuthNavigation,
    App: AppNavigation
  },
  {
    initialRouteName: 'Auth'
  }
)

const AppContainer = createAppContainer(SwitchNavigator)

export default AppContainer

LoginScreen.js

import React, { memo, useState } from 'react';
import { TouchableOpacity, StyleSheet, Text, View } from 'react-native';
import Background from '../Components/Background';
import Logo from '../Components/Logo';
import Header from '../Components/Header';
import Button from '../Components/Button';
import TextInput from '../Components/TextInput';
import BackButton from '../Components/BackButton';
import { theme } from '../CustomProperties/Themes';
import { emailValidator, passwordValidator } from '../CustomProperties/utils';
import Login from '../Components/Login';


const LoginScreen = ({ navigation }) => {
  
  const [email, setEmail] = useState({ value: '', error: '' });
  const [password, setPassword] = useState({ value: '', error: '' });

  const _onLoginPressed = () => {
    const emailError = emailValidator(email.value);
    const passwordError = passwordValidator(password.value);

    if (emailError || passwordError) {
      setEmail({ ...email, error: emailError });
      setPassword({ ...password, error: passwordError });
      return;
    }
    else {
      const login = new Login();
      login.realmLogin(email.value, password.value);
    }
  };

  return (
    <Background>
      <BackButton goBack={() => navigation.navigate('HomeScreen')} />

      <Logo />

      <Header>Welcome back.</Header>

      <TextInput
        label="Email"
        returnKeyType="next"
        value={email.value}
        onChangeText={text => setEmail({ value: text, error: '' })}
        error={!!email.error}
        errorText={email.error}
        autoCapitalize="none"
        autoCompleteType="email"
        textContentType="emailAddress"
        keyboardType="email-address"
      />

      <TextInput
        label="Password"
        returnKeyType="done"
        value={password.value}
        onChangeText={text => setPassword({ value: text, error: '' })}
        error={!!password.error}
        errorText={password.error}
        secureTextEntry
      />

      <View style={styles.forgotPassword}>
        <TouchableOpacity
          onPress={() => navigation.navigate('ForgotPasswordScreen')}
        >
          <Text style={styles.label}>Forgot your password?</Text>
        </TouchableOpacity>
      </View>

      <Button mode="contained" onPress={_onLoginPressed}>
        Login
      </Button>

      <View style={styles.row}>
        <Text style={styles.label}>Don’t have an account? </Text>
        <TouchableOpacity onPress={() => navigation.navigate('RegisterScreen')}>
          <Text style={styles.link}>Sign up</Text>
        </TouchableOpacity>
      </View>
    </Background>
  );
};

const styles = StyleSheet.create({
  forgotPassword: {
    width: '100%',
    alignItems: 'flex-end',
    marginBottom: 24,
  },
  row: {
    flexDirection: 'row',
    marginTop: 4,
  },
  link: {
    fontWeight: 'bold',
  },
});

export default memo(LoginScreen);

Login.js

import React, { Component } from 'react';
import {
    Alert,
    Button,
    KeyboardAvoidingView,
    Image,
    StyleSheet,
    Text,
    TouchableHighlight,
    View
} from 'react-native';

import Auth0 from 'react-native-auth0';

var credentials = require('../auth0-credentials');
const auth0 = new Auth0(credentials);


export default class Login {

    constructor(props) {
        //super(props);
        this.state = { viewLogin: true };
        this.realmLogin = this.realmLogin.bind(this);
        this.createUser = this.createUser.bind(this);
    }
        navigateHomeApp() {
            this.props.navigation.navigate("App");
        };

    onSuccess(credentials) {
        auth0.auth
            .userInfo({ token: credentials.accessToken })
            .then(profile => {
                //console.log(credentials);
                //console.log(profile);
                this.props.onAuth(credentials, profile);
            })
            .catch(console.error);
    }

    alert(title, message) {
        Alert.alert(
            title,
            message,
            [{ text: 'OK', onPress: () => console.log('OK Pressed') }],
            { cancelable: false }
        );
    }

    realmLogin(username, password) {
        auth0.auth
            .passwordRealm({
                username: username,
                password: password,
                realm: 'Username-Password-Authentication',
                scope: 'openid profile email',
                audience: 'https://' + credentials.domain + '/userinfo'
            })
            .then(credentials => {
                this.onSuccess(credentials);
                this.navigateHomeApp();
            })
            .catch(console.error);
    }

    createUser(username, password) {
        auth0.auth
            .createUser({
                email: username,
                password: password,
                connection: 'Username-Password-Authentication',
            })
            .then(success => {
                console.log(success)
                this.alert('Success', 'New user created')
                //navigation.navigate('LoginScreen');
            })
            .catch(error => { 
                this.alert('Error', error.json.description) 
            });
    }

    webAuth(connection) {
        auth0.webAuth
            .authorize({
                scope: 'openid profile email',
                connection: connection,
                audience: 'https://' + credentials.domain + '/userinfo'
            })
            .then(credentials => {
                this.onSuccess(credentials);
            })
            .catch(error => this.alert('Error', error.error_description));
    };

}

听起来像我无法访问最初在LoginScreen上声明的导航对象

const LoginScreen = ({ navigation })

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

您正在Login.js类(仅是实用程序类)中调用 this.props.navigation.navigate(“ App”)。导航在组件中起作用

LoginScreen.js

const onNavigateCallback = () => {
  this.props.navigation.navigate("App");
}

const _onLoginPressed = () => {
    ........

    if (emailError || passwordError) {
      ......
    }
    else {
      const login = new Login();
      login.realmLogin(email.value, password.value, onNavigateCallback); // Add this here
    }
  };

Login.js

realmLogin(username, password, callback = undefined) {
        auth0.auth
            .passwordRealm({
                username: username,
                password: password,
                realm: 'Username-Password-Authentication',
                scope: 'openid profile email',
                audience: 'https://' + credentials.domain + '/userinfo'
            })
            .then(credentials => {
                this.onSuccess(credentials);
                // this.navigateHomeApp(); // remove this from here
               if(callback) callback(); // Add this here
            })
            .catch(console.error);
    }

答案 1 :(得分:0)

尝试

navigateHomeApp =()=> {
            this.props.navigation.navigate("App");
        };