晚安社区!
当我尝试使用我的自定义钩子时,我目前收到此错误。
这个自定义钩子有 3 个参数,一个初始状态,一个验证规则和一个动作函数。
目前验证我的数据显示为未定义。
//This is the custom Hook!
import React, { useState, useEffect } from 'react';
const useValidacion = (stateInicial, validar, fn) => {
const [ valores, guardarValores ] = useState(stateInicial);
const [ errores, guardarErrores ] = useState({});
const [ submitForm, guardarSubmitForm ] = useState(false);
useEffect(() => {
if(submitForm) {
const noErrores = Object.keys(errores).lenght === 0;
if(noErrores) {
fn(); //Funcion que se este ejecutando
}
guardarSubmitForm(false);
}
}, [errores])
// Funcion que se ejecuta cuando el usuario escribe
const handleChange = e => {
guardarValores({
...valores,
[e.target.name]: e.target.value
})
}
//Funcion que se ejecuta cuando el usuario da submit
const handleSubmit = e => {
e.preventDefault();
const erroresValidacion = validar(valores);
guardarErrores(erroresValidacion);
guardarSubmitForm(true);
}
return {
valores,
errores,
submitForm,
handleChange,
handleSubmit
}
}
export default useValidacion;
这些是规则:
export default function validarCrearCuenta(valores) {
let errores = {};
// Validar el nombre
if(valores.nombre.trim() === '') {
errores.nombre = "El nombre es obligatorio"
}
// Validar el correo
if(!valores.email.trim() === '') {
errores.email = "El correo es obligatorio"
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(valores.email)) {
errores.email = "Correo no valido"
}
// Validar contraseña
if(!valores.password === '') {
errores.password = "La contraseña es obligatorio"
} else if(valores.password.lenght < 6) {
errores.password = "La contraseña debe ser de al menos 6 caracteres"
}
}
我真的很感激这方面的帮助。
是否validar
曾经返回 null 或 undefined?
很可能errores
在某个时候变成 null 或 undefined,可能是当它被设置为validar(valores)
in的返回值时handleSubmit
。
然后我们调用Object.keys(null)
的useEffect
,并导致错误。
编辑:啊,是的,我看到该validar
函数没有返回值。加return errores
在最后就好了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句