用户认证后导航到另一个屏幕

时间:2020-02-17 21:36:04

标签: react-native

我在Firebase数据库中有一些用户的登录应用程序。当用户成功登录其帐户时,我要将其重定向到我拥有的另一个屏幕。不幸的是,几天以来我尝试过的每一种方法都无法按预期工作。

这是我的代码,我省略了StyleSheet和库(是的,我将其他屏幕导入了App.js)

class HomeScreen extends Component {
  state = { username: null, password: null, nonValidInput: null }

  _onSubmit = ({ navigation }) =>{
    const { navigate } = this.props.navigation;

    if(EmailValidator.validate(this.state.username) == true) {
      this.setState({ nonValidInput: false });
      const { username, password } = this.state;

      try {
        firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(navigator.navigate('Age'));
      } catch {
        Alert.alert(
          'Error',
          'Los datos no son correctos',
          [
            { text: 'Ok' }
          ],
          { cancelable: false }
        );
      }

    } else { 
      this.setState({ nonValidInput: true });
    }
  }

  render() {
    return (
      <KeyboardAwareScrollView contentContainerStyle={styles.container} scrollEnabled 
      enableOnAndroid={true} resetScrollToCoords={{x:0, y:0}}> 
        <View style={styles.logo}>
          <Image source = {logo} style={styles.img}/>
          <Text style={styles.textLogoPrimary}>Neuron App</Text>
          <Text style={styles.textLogoSecondary}>Test</Text>
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Correo Electrónico</Text>
          <TextInput keyboardType='email-address' placeholder='Email' onChangeText={value => this.setState({ username: value })} 
          style={styles.formInput} />
          {this.state.nonValidInput ? (
            <Text style={styles.textAlert}>Correo electrónico no valido.</Text> 
          ) : null}       
        </View>

        <View style={styles.formElement}>
          <Text style={styles.formText}>Contraseña</Text>
          <TextInput style={styles.formInput} placeholder='Contraseña' onChangeText={value => this.setState({ password: value })} 
          secureTextEntry={true}/>
        </View>

        <View style={styles.buttonView}>
          <TouchableOpacity style={styles.button} onPress={this._onSubmit}>
            <Text style={styles.buttonText}>Iniciar</Text>
          </TouchableOpacity>
        </View>     
      </KeyboardAwareScrollView>
    );
  }
}

const Stack = createStackNavigator();

class App extends Component {
  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{headerShown: false}} initialRouteName="Home">
          <Stack.Screen name='Home' component={HomeScreen} />
          <Stack.Screen name='Age' component={AgeInput} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

什么是navigator?您可以直接从导航道具使用导航:

firebase.auth().signInWithEmailAndPassword(this.state.username, this.state.password).then(() => this.props.navigation.navigate('Age'));

此外,请确保以正确的方式在then子句中调用该函数。