如何在没有硬编码的情况下将电子邮件和全名从登录屏幕传递到主屏幕

问题描述 投票:0回答:0

我一直遇到问题 WARN 警告:未处理的错误从 submitForm() [TypeError: Cannot read property 'user' of undefined]
错误类型错误:无法读取未定义的属性“用户”

登录屏幕

import React, {useState, useEffect} from 'react';
import { StyleSheet, View, Image, Keyboard, KeyboardAvoidingView, Platform } from 'react-native';

import { MaterialCommunityIcons } from '@expo/vector-icons';
import { Formik } from 'formik';
import * as Yup from 'yup';

import AppButton from '../components/AppButton';
import AppColors from '../config/AppColors';
import AppLogoText from '../components/AppLogoText';
import AppScreen from '../components/AppScreen';
import AppTextInput from '../components/AppTextInput';
import AppText from '../components/AppText';

const schema = Yup.object().shape(
    {
        email: Yup.string().required().email().label("Email"),
        password: Yup.string().required().min(4).max(8).label("Password"),
    }
);

const users = [
    {
        id: "user1",
        name: "Harry Elliot",
        email: "[email protected]",
        password: "12345678",
    },
    {
        id: "user2",
        name: "Ellie Elliot",
        email: "[email protected]",
        password: "12345678",
    }
];

const validateUser = ({email, password}) => {
    return(
        users.filter((user) => user.email === email && user.password === password).length>0
    );
};

const getUser = ({email}) => {
    return users.find((user) => user.email === email);
}

function LoginScreen({navigation}) {
    
    const [showPassword, setShowPassword] = useState(false);
    const [isKeyboardActive, setIsKeyboardActive] = useState(false);
    
    useEffect(() => {
        Keyboard.addListener("keyboardDidShow", () => setIsKeyboardActive(true));
        Keyboard.addListener("keyboardDidHide", () => setIsKeyboardActive(false));
    
        return () => {
            Keyboard.removeListener("keyboardDidShow", () => setIsKeyboardActive(true));
            Keyboard.removeListener("keyboardDidHide", () => setIsKeyboardActive(false));
        };
    }, []);

    return (
        <AppScreen>
            {!isKeyboardActive && (
            <View style={styles.LoginContainer}>
                <Image
                    style={styles.Logo}
                    source={require('../assets/MyImages/WorldChangerLogo.png')}
                />
                <AppLogoText style={styles.LogoText}>WORLDCHANGER</AppLogoText>
            </View>
            )}
            <KeyboardAvoidingView 
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                style={styles.KeyboardAvoidingView}>   
                <Formik
                    initialValues = {{email: '', password: '',}}
                    onSubmit={(values, { resetForm }) => {
                        if (validateUser(values)) {
                          resetForm();
                          navigation.navigate("Home");
                        } else {
                          resetForm();
                          alert("Invalid Login Details");
                        }
                      }}
                    validationSchema = {schema}>
                    {({values, handleChange, handleSubmit, touched, setFieldTouched, errors})=> (
                    <>
                    <View style={styles.TextInputContainer}>
                        <AppTextInput
                            icon="email"
                            placeholder="Email"
                            keyboardType="email-address"
                            autoCapitalize="none"
                            autoCorrect={false}
                            textContentType="emailAddress"
                            value={values.email}
                            onBlur={() => setFieldTouched("email")}
                            onChangeText = {handleChange("email")}
                        />
                        {touched.email && <AppText style={styles.ErrorMessages}>{errors.email}</AppText>}
                        <View style={styles.PasswordContainer}>
                            <AppTextInput
                                icon="lock"
                                placeholder="Password"
                                secureTextEntry={!showPassword}
                                textContentType="password"
                                value={values.password}
                                onBlur={() => setFieldTouched("password")}
                                onChangeText={handleChange("password")}
                            />
                            <View style={styles.PasswordIconContainer}>
                                <MaterialCommunityIcons
                                    name={showPassword ? 'eye-off' : 'eye'}
                                    size={20}
                                    color={AppColors.mediumGrey}
                                    onPress={() => setShowPassword(!showPassword)}
                                    style={styles.PasswordIcon}
                                />
                            </View>
                        </View>
                        {touched.password && <AppText style={styles.ErrorMessages}>{errors.password}</AppText>}
                    </View>
                    <View style = {styles.ButtonContainer}>
                        <AppButton title="LOGIN" onPress={handleSubmit}/>
                    </View>
                    </>
                    )}
                </Formik>
            </KeyboardAvoidingView>
        </AppScreen>
    );
}

主屏幕

import React, { useState } from 'react';
import { StyleSheet, View, Image, TouchableOpacity } from 'react-native';

import * as ImagePicker from 'expo-image-picker';

import AppButton from '../components/AppButton';
import AppColors from '../config/AppColors';
import AppIcon from '../components/AppIcon';
import AppProfileItems from '../components/AppProfileItems';
import AppScreen from '../components/AppScreen';



function HomeScreen({ navigation}) {
  
  const [imageUri, setImageUri] = useState(null);

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      alert('Sorry, we need camera roll permissions to make this work!');
      return;
    }
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    if (!result.canceled) {
      setImageUri(result.uri);
    }
  };

  return (
    <AppScreen>
      <View style={styles.AccountContainer}>
        <TouchableOpacity style={styles.IconContainer} onPress={pickImage}>
          {imageUri ? (
            <Image source={{ uri: imageUri }} style={styles.Icon} />
          ) : (
            <AppIcon
              name="account-plus-outline"
              size={100}
              iconColor={AppColors.darkBlue}
            />
          )}
        </TouchableOpacity>
        <AppProfileItems 
          FullName={"Harry Elliot"} 
          Email={"[email protected]"} />

        <View style={styles.ButtonContainer}>
          <AppButton
            title="LOGOUT"
            onPress={() => navigation.navigate('Logout')}
          />
        </View>
      </View>
    </AppScreen>
  );
}

我一直在尝试使用路由,但我总是遇到问题,比如

WARN 警告:未处理的错误从 submitForm() [TypeError: Cannot read property 'user' of undefined]
错误类型错误:无法读取未定义的属性“用户”

react-native react-navigation react-native-navigation
© www.soinside.com 2019 - 2024. All rights reserved.