axios 当我按下React Native中的按钮时,如何执行函数?

umuewwlo  于 2023-03-02  发布在  iOS
关注(0)|答案(1)|浏览(126)

我正在尝试执行一个函数(Save),它向我在Node js中的API发出一个post请求;这个请求使用Axios。在表单中,我使用Formik和Yup进行验证。表单是一个简单的登录。我一直在关注这个博客:
https://blog.logrocket.com/react-native-form-validations-with-formik-and-yup/
显然,还有Formik、Yup、Axios和React Native的文档。
问题是保存功能不执行,根本不起作用。当我按下按钮时,该功能不运行。
当我使用
console.log(values)
我得到了所有的值。但是,当我使用:
Save(Values)
函数不执行。
我可以在FormikDoc中看到,我需要在按钮组件上使用此功能

onPress={handleSubmit}

但它也不起作用。
我和博客作者做的是一样的,我认为handleSubmit函数是这个库自己的,我不需要添加其他的东西,但实际上我不确定。
在这里代码:

import React from 'react';
import { View, Image, Text, TouchableOpacity, TextInput, Button } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import * as Yup from 'yup';
import { Formik } from 'formik'
import Background from './../../components/Background';
import { API } from "./../../config/config";
import Btn from './../../components/Btn';

const LoginSchema = Yup.object().shape({
    email: Yup.string()
        .min(6, "Demasiado corto")
        .max(100, "Demasiado largo")
        .email("No corresponde a un email válido.")
        .required("Requerido"),
    pwd: Yup.string()
        .min(8, "Demasiado corto")
        .max(100, "Demasiado largo")
        .required("Requerido"),
});

const Login = (props) => {

    const loginform = {
        email: '',
        pwd: ''
    }

    const Save = (value) => {
        console.log(value);
        axios({
            method: 'post',
            url: `${API}/login`,
            data: {
                email: value.email,
                pwd: value.pwd
            },
        }).then((response) => {
            let data = response.data;
            if (data.OK === true) {
                alert("Bienvenido " + data.User.Usuario[0].NombreCompleto);
                props.navigation.navigate("Home")
                AsyncStorage.setItem(
                    'TOKEN',
                    data.TOKEN,
                );
            } else {
                if (data.OK === false) {
                    Alert(data.message, 2)
                }
            }
        }).catch((e) => {
            let error = e.message;
            if (error.OK === false) {
                alert(error.message)
            }
        })
    }

    return (
        <Background>
            <View style={{ alignItems: 'center', width: 460 }}>
                <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', marginRight: 50, marginTop: 100 }}>
                    <Image source={require('./../../assets/Logo.png')} />
                </View>
                <View
                    style={{
                        felx: 1,
                        height: 700,
                        width: '100%',
                        paddingTop: 40,
                        marginRight: 50,
                        alignItems: 'center',
                    }}>
                    <Formik
                        initialValues={loginform}
                        validationSchema={LoginSchema}
                        onSubmit={values => console.log(values) }
                    >
                        {({ handleChange, handleBlur, handleSubmit, values, errors, touched, isValid, }) => (
                            <View>
                                <TextInput
                                    name="email"
                                    placeholder="Email"
                                    onChangeText={handleChange('email')}
                                    onBlur={handleBlur('email')}
                                    value={values.email}
                                    keyboardType="email-address"
                                    style={{ paddingHorizontal: 30, backgroundColor: 'white', marginVertical: 10, width: '60%' }}
                                    placeholderTextColor='gray'>
                                </TextInput>
                                {(errors.email && touched.email) &&
                                    <Text style={{ fontSize: 10, color: 'red' }}>{errors.email}</Text>
                                }
                                <TextInput
                                    name="pwd"
                                    placeholder="Contraseña"
                                    onChangeText={handleChange('pwd')}
                                    onBlur={handleBlur('pwd')}
                                    value={values.pwd}
                                    secureTextEntry={true}
                                    style={{ paddingHorizontal: 30, backgroundColor: 'white', marginVertical: 10, width: '60%' }}
                                    placeholderTextColor='gray'>
                                </TextInput>
                                {(errors.pwd && touched.pwd) &&
                                    <Text style={{ fontSize: 10, color: 'red' }}>{errors.pwd}</Text>
                                }
                                <View
                                    style={{ alignItems: 'flex-start', width: '60%', paddingRight: 10, marginBottom: 10 }}>
                                    <TouchableOpacity onPress={() => props.navigation.navigate("RecuperarPWD")}>
                                        <Text style={{ color: 'white', fontWeight: 'bold', fontSize: 16 }}>
                                            ¿Olvidó su contraseña?
                                        </Text>
                                    </TouchableOpacity>
                                </View>
                                <Button style={{ color: 'white', width: 200, backgroundColor: '#FF8029'}} onPress={handleSubmit} title="Iniciar Sesión" disabled={!isValid}/>
                            </View>
                        )}
                    </Formik>
                    <View style={{ display: 'flex', flexDirection: 'row', justifyContent: "center" }}>
                        <Btn textColor='white' width={365} bgColor='#FF8029' mt={120} mr={15} btnLabel="¿Aún no tienes una cuenta? ¡Registrate!" Press={() => props.navigation.navigate("Registro")} />
                    </View>
                </View>
            </View>
        </Background>
    );
};

export default Login;

谢谢,我期待你的帮助😊

hfsqlsce

hfsqlsce1#

使用onSubmit

<Formik
    ...
    onSubmit={Save}
>

相关问题