繁体   English   中英

React Hook Form - formState 未定义

[英]React Hook Form - formState is not defined

我正在尝试在我的 react 应用程序中使用 React-Hook-Forms,并且我使用的是 react-hook-form 版本 7,我收到一个错误,提示“未定义 formState ”,尽管它已正确导入和使用。 这是我在我的应用程序中使用的一段代码,根据此处提供的文档正确显示:- https://react-hook-form.com/api/useform/formstate

const LoginForm = () => {
const { register, setError ,formState: { errors }, handleSubmit } = useForm();
const {sendSignInLinkToEmail} = useAuth();

const onSubmit = async data => {
    // console.log(data);
    try{
        await sendSignInLinkToEmail(data.email);
    }catch (error) {
        setError("email", {
            type: "manual",
            message: error.message,
        });
    }
}

console.log(errors);
return(
    <GridItem>
      
        { errors.email && (
            <Alert status="error" variant="subtle" mt={6} mb={6}>
                <AlertIcon />
                {errors.email.message}
            </Alert>
        )}

        {formState.isSubmitSuccessful && (
            <Alert status="success" variant="subtle" mt={6} mb={6}>
            <AlertIcon />
            Check your email to complete login !!
        </Alert>
        )}
        <form onSubmit={handleSubmit(onSubmit)}>
            <FormControl>
                <FormLabel htmlFor="email">Email</FormLabel>
                <Input name="email" placeholder="Email" {...register('email')}></Input>
                <Button mt={4} colorScheme="teal" isLoading={formState.isSubmitting} type="submit">Login</Button>
            </FormControl>
        </form>
    </GridItem>
)
}

但我收到了这个错误

Line 50:14:  'formState' is not defined  no-undef
Line 60:66:  'formState' is not defined  no-undef

第 50 行是

{formState.isSubmitSuccessful && (
        <Alert status="success" variant="subtle" mt={6} mb={6}>
        <AlertIcon />
        Check your email to complete login !!
    </Alert>
    )}

第 60 行是

<Button mt={4} colorScheme="teal" isLoading={formState.isSubmitting} type="submit">Login</Button>

来自 useForm 的错误也没有得到正确实现,setError 没有设置“错误” object 发生的错误,这里出了什么问题?

由于您将 formState 解构为错误{formState:{errors}}只会返回错误,因此您可以使用 formState 的 rest 道具,而不会出现像{formState:{errors, ...formState}}或类似的错误,或者只是简单地使用formState.errors

您还应该使用register正确应用验证。

在这里阅读:

https://react-hook-form.com/api/useform/register/

暂无
暂无

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

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