【问题标题】:React Hook Form - formState is not definedReact Hook Form - formState 未定义
【发布时间】:2022-01-06 04:27:45
【问题描述】:

我正在尝试在我的 react 应用程序中使用 React-Hook-Forms,并且我使用的是 react-hook-form 版本 7,但我收到一条错误消息,提示“formState is not defined "虽然它是正确导入和使用的。 这是我在我的应用程序中使用的一段代码,根据此处提供的文档显示正确:- 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 的 errors 没有正确实现,setError 没有设置“错误”对象与发生的错误,这里出了什么问题?

【问题讨论】:

    标签: reactjs react-hooks react-hook-form


    【解决方案1】:

    由于您将 formState 解构为错误{formState:{errors}} 只会返回错误,因此您可以在没有错误的情况下使用 formState 的其余道具,例如{formState:{errors, ...formState}} 或类似的东西,或者只是使用formState.errors

    【讨论】:

    • 这行得通,我使用了 formState.errors,一切正常,谢谢
    【解决方案2】:

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

    在这里阅读:

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

    【讨论】:

    • 感谢您,我浏览了文档并找到了正确的方法,似乎我正在查看更新版本的文档并使用旧版本的 react-hook-form。谢谢!!
    猜你喜欢
    • 2021-10-20
    • 2021-07-28
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    相关资源
    最近更新 更多