简体   繁体   English

在捕获错误处理程序中反应本机显示对话框或弹出窗口

[英]React Native show Dialog or Popup in catch error handler

I am very new to React Native and try to show a popup if an error ist throwen.我对 React Native 很陌生,如果抛出错误,我会尝试显示一个弹出窗口。 But I dont get it to work.但我不让它工作。 Thats my code:那是我的代码:

import React, { useState, useEffect } from 'react'
import { Alert, Modal, TouchableOpacity, StyleSheet, View, Pressable } from 'react-native'
import { Text } from 'react-native-paper'
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 '../core/theme'
import { emailValidator } from '../helpers/emailValidator'
import { passwordValidator } from '../helpers/passwordValidator'
import Icon from 'react-native-vector-icons/FontAwesome5';


export default function LoginScreen({ navigation }) {

  const [email, setEmail] = useState({ value: '', error: '' })
  const [password, setPassword] = useState({ value: '', error: '' })
  const [hidePass, setHidePass] = useState(true);
  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 SignUp = async () => {
    try {
      const response = await fetch('https://www.ecample.com/endpoint', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: email.value,
          password: password.value
        })
      })
      let json = await response.json()
      if ((typeof json.token !== 'undefined') && (json.token.length > 230)) {

        alert('fdgdg')

      } else {
        navigation.reset({
          index: 0,
          routes: [{ name: 'ErrorPage' }],
        })
      }
    } catch (err) {
      console.log(err)
            return (
                <View style={styles.centeredView}>
                  <Modal
                    animationType="slide"
                    transparent={true}
                    visible={modalVisible}
                    onRequestClose={() => {
                      Alert.alert("Modal has been closed.");
                      setModalVisible(!modalVisible);
                    }}
                  >
                    <View style={styles.centeredView}>
                      <View style={styles.modalView}>
                        <Text style={styles.modalText}>Hello World!</Text>
                        <Pressable
                          style={[styles.button, styles.buttonClose]}
                          onPress={() => setModalVisible(!modalVisible)}
                        >
                          <Text style={styles.textStyle}>Hide Modal</Text>
                        </Pressable>
                      </View>
                    </View>
                  </Modal>
                  <Pressable
                    style={[styles.button, styles.buttonOpen]}
                    onPress={() => setModalVisible(true)}
                  >
                    <Text style={styles.textStyle}>Show Modal</Text>
                  </Pressable>
                </View>
              );
    }

  }     

    } // ende else
  }

  
  
  
  return (

      
      
      
    <Background>
  
      <BackButton goBack={navigation.goBack} />
      <Logo />
      <Header>Bitte geben Sie Ihre Daten ein.</Header> 
      
      <TextInput
        label="E-Mail"
        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="Passwort"
        returnKeyType="done"
        value={password.value}
        onChangeText={(text) => setPassword({ value: text, error: '' })}
        error={!!password.error}
        errorText={password.error}
       secureTextEntry={hidePass ? true : false}
      />
        <Icon style={styles.eyeContainer}
              name={hidePass ? 'eye-slash' : 'eye'}
              size={15}
              color="grey"
              onPress={() => setHidePass(!hidePass)}
            />    

      <View style={styles.forgotPassword}>
        <TouchableOpacity
          onPress={() => navigation.navigate('ResetPasswordScreen')}
        >
          <Text style={styles.forgot}>Passwort vergessen?</Text>
        </TouchableOpacity>
      </View>


      <Button color="#1584a5" mode="contained" onPress={onLoginPressed}>
        Login
      </Button>
          
          
      <View style={styles.row}>
        <Text>Keinen Account? </Text>
        <TouchableOpacity onPress={() => navigation.replace('RegisterScreen')}>
          <Text style={styles.link}>Jetzt registrieren</Text>
        </TouchableOpacity>
      </View>
          
    </Background>
         
  )
}

I tryed for two days now different modules and scripts but I cant get a popup.我尝试了两天不同的模块和脚本,但我无法弹出。 The endpoinz works fine.端点工作正常。 I recive a token, an error 403 or an html with 503 as answer.我收到了一个令牌、一个错误 403 或一个 html 和 503 作为答案。 Therefor I used the catch error.因此我使用了 catch 错误。

I nearly tried every Modal, Popup, Alert which I could find in the Internet:( I need urgent help please.我几乎尝试了所有在 Internet 上可以找到的 Modal、Popup、Alert:(我需要紧急帮助。

You can use Alert component from react-native.您可以使用 react-native 中的警报组件。

fetchEvents() {
   fetch('http://www.wrongurl.com', {
     method: 'GET',
     redirect: 'follow'
   })
   .then(function(response) {
       if (response.status == 200) {
           let responseText = JSON.stringify(response.text());
           console.log(responseText);
       }
     else throw new Error('HTTP response status not code 200 as expected.');
   })
    .catch(function(error) {
       Alert.alert(error);   // Using this line
   });
}
const SignUp = async () => { try { const response = await fetch('https://www.example.com/endpoint', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ username: email.value, password: password.value }) }) if (response.status === 200) { let json = await response.json() if ((typeof json.token !== 'undefined') && (json.token.length > 230)) { alert('fdgdg') } else { navigation.reset({ index: 0, routes: [{ name: 'ErrorPage' }], }) } } else { throw new Error(`failed due to status code ${response.status}`); } } catch (err) { console.log(err) // write code to open modal here //openErrorModal(err) } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM