我忘记了密码页面,该页面显然需要电子邮件输入。提交表单后,我将显示一条 Toast 通知,确认操作成功或错误。
我创建了一个通知组件,当我的应用程序状态填充了通知对象时就会呈现该组件。
通过提交表单,我将调度一个填充通知对象的操作。 效果很好
但是在发送后,表单会丢失其字段值
const {control, handleSubmit, setError, formState: {errors}, isSubmitting} = useForm({defaultValues: {email: ''}})
这是我的表单提交处理程序
const onSubmit = async data => {
if (Object.values(data).every(field => field.length > 0)) {
useJwt
.forgotPassword({email: data.email})
.then(res => dispatch(toastNotify({ status: "success", ...res.message })))
.catch(({response}) => {
if (response.status === 400 && response.data.hasOwnProperty('errors')) {
response.data.errors.forEach(error => setError(error['param'], {type: 'manual', message: error['msg']}))
} else {
// If I comment line below and log the response data, form values works fine
dispatch(toastNotify({type: "error", ...response.data}))
}
})
} else {
for (const key in data) {
if (data[key].length === 0) {
setError(key, {
type: 'manual'
})
}
}
}
}
这是我的表格
<Form className='auth-forgot-password-form mt-2' onSubmit={handleSubmit(onSubmit)}>
<div className='mb-2'>
<Label className='form-label' for='email'>
Email
</Label>
<Controller
id='email'
name='email'
control={control}
render={({field}) => (
<Input type='text' id='email' name='email' autoFocus invalid={errors.email && true} {...field} />
)}
/>
{errors && errors.email && <FormFeedback>{ errors.email.message }</FormFeedback>}
</div>
<Button color='primary' disabled={isSubmitting} block>
{isSubmitting ? <Spinner size='sm' /> : 'Send reset link'}
</Button>
</Form>
你解决这个问题了吗?我工作中也遇到同样的问题