簡體   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