react-native登录屏幕-按下登录按钮且登录字段为空时出错

时间:2018-12-14 22:36:38

标签: react-native login null

我有一个简单的登录屏幕,要求输入电子邮件和密码。

Login Screen

如果按下“登录”按钮,并且两个字段均为空白,则会出现此错误:“ null不是对象(正在评估'_this.state.Email')”

Error Screen

代码如下:

import React, {Component} from 'react';
import {View, Button, ScrollView, AsyncStorage, Alert } from 'react-native';
import colors from '../config/colors';
import { TextInput } from '../components/TextInput';

class SignIn extends Component {
    signIn = () => {

        const {Email} = this.state;
        const {Password} = this.state;

        fetch('http://192.168.1.3/Restaurant_App/php/sign_in.php', {
            method: 'POST',
            headers: {
            'Accept': 'application/json',
            'Content-Type': 'application.json',
            },
            body: JSON.stringify({
            email: Email,
            password: Password,
            })
        }).then((response) => response.json())
        .then((responseJson) => {
            if (responseJson == Email) {
                Alert.alert(responseJson);
                AsyncStorage.setItem('email', Email);
                this.props.navigation.navigate('Search');
            } else {
                Alert.alert(responseJson);
            }
        }).catch((error) => {
            console.error(error);
        });
    };
    render() {
        return (
            <View>
                <ScrollView style={{ backgroundColor: colors.background }}>
                    <TextInput
                        placeholder="Email..."
                        onChangeText={Email => this.setState({Email})}
                    />
                    <TextInput
                        placeholder="Password..."
                        secureTextEntry={true}
                        onChangeText={Password => this.setState({Password})}
                    />
                </ScrollView>
                <Button
                    onPress={() => this.signIn()}
                    title="Sign In"
                />
            </View>
        );
    }
}
export default SignIn;

我希望这样,如果在空白字段中按下“登录”按钮,则不会出现此错误。相反,应该有一个警告,提示“请填写所有字段”。或类似的东西。

2 个答案:

答案 0 :(得分:0)

您可以在登录功能顶部执行以下操作:

If(this.state.email.length === 0  || this.state.password.length === 0) {
alert(“please complete the fields”);
return;}

答案 1 :(得分:0)

您应该在进行提取请求之前进行一些验证检查。

您可以这样做

signIn = () => {

    const {Email, Password} = this.state;
    if(!this.checkDetails(Email, Password) {
      // you could show an alert here, but it is not great UX, 
      // you should show your user where they have gone wrong, 
      // by making style changes, a red border around the TextInput, 
      // text explaining what has gone wrong.
      return;
    }

    fetch('http://192.168.1.3/Restaurant_App/php/sign_in.php', {
        ...
    }).then((response) => response.json())
    .then((responseJson) => {
        ...
    }).catch((error) => {
        console.error(error);
    });
};

checkDetails = (Email, Password) => {

  // check that it is a valid email address
  // this is a regex that I have used in the past to check email addresses.
  const emailIsValid = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(Email);

  // if the password has a minimum length then you should use that rather than 0
  this.setState({emailIsValid, passwordIsValid: Password.length > 0});
  if (emailIsValid && Password.length > 0) return true;
  return false;
}

使用这些新的状态值表示电子邮件和密码有效,您可以在错误或缺失的字段旁边设置其他样式和错误文本。

<TextInput
   placeholder="Email..."
   onChangeText={Email => this.setState({Email})}
   styles={this.state.emailIsValid ? styles.validEmail : styles.invalidEmail}
 />
 {!this.state.emailIsValid && <Text>Please input a valid email</Text>}
 <TextInput
   placeholder="Password..."
   secureTextEntry={true}
   onChangeText={Password => this.setState({Password})}
   styles={this.state.passwordIsValid ? styles.validPassword : styles.invalidPassword}
 />
 {!this.state.passwordIsValid && <Text>Please input a valid password</Text>}

不要为了不同的状态设置样式。

const styles = StyleSheet.create({
  validEmail: {},
  validPassword: {},
  invalidEmail: {},
  invalidPassword: {}
});

您可能需要为emailIsValid和passwordIsValid添加初始状态值,以便将它们设置为true,以便显示正确的样式。另外,您应该定义电子邮件和密码的初始状态。

向您的课程添加构造函数

constructor (props) {
   super(props);
   this.state = {
       Email: '',
       Password: '',
       emailIsValid: true,
       passwordIsValid: true
   }
}

我希望这会有所帮助。