react-hook-form 将表单撤销到之前的状态

react-hook-form undo the form to previous state

我用 react-hook-form 的 setValue 函数填充了一个表单(我不知道这是否是在编辑模式下设置表单的最佳方式)。

一旦用户触摸了表单,我希望(单击按钮)将表单恢复到我之前设置的状态, (注意,我不想重置它,而是将其重新设置为我之前设置的值)

const { register, handleSubmit, watch, reset, errors, setValue } = useForm();
const { id } = useParams()
const { loading, error, data } = useQuery(GET_FBUSER,{
        variables: {_id: id},
        skip: id === undefined
    });
useEffect(() => {
        if (data) {
            const {_id, id, fbId, name} = data.FBUser[0]
            setValue('_id',_id);
            setValue('id',id);
            setValue('fbId',fbId);
            setValue('name',name);
        }
    }, [data])


<form onSubmit={handleSubmit(onSubmit)}>
                <Grid container spacing={3}>
                    <Grid item xs={4}>
                        <TextField fullWidth inputRef={register} InputLabelProps={{ shrink: true }} InputProps={{readOnly: true}} name="_id"  label="_Id" variant="outlined" />
                    </Grid>
                    <Grid item xs={8}>
                        <TextField fullWidth inputRef={register} InputLabelProps={{ shrink: true }} InputProps={{readOnly: true}} name="id"  label="Id" variant="outlined" />
                    </Grid>
                    <Grid item xs={12}>
                        <TextField fullWidth  inputRef={register} InputLabelProps={{ shrink: true }}  name="name"  label="Name" variant="outlined" />
                    </Grid>
                    <Grid item xs={12}>
                        <TextField fullWidth error={errors.fbId} inputRef={register({required : true})} InputLabelProps={{ shrink: true , required: true}}   name="fbId"  label="Facebook Id" variant="outlined" />
                    </Grid>
                    <Grid item xs={12}>
                        <TextField fullWidth  inputRef={register}  InputLabelProps={{ shrink: true }}  name="note"  label="Note" variant="outlined" />
                    </Grid>
                    <Grid item xs={12}>
                        <Button type="submit" variant="contained" color="primary" startIcon={<SaveIcon/>}>Salva</Button>
                        <Button  onClick={reset} variant="contained" color="primary" startIcon={<CancelIcon/>}>Annulla</Button>
                    </Grid>
                </Grid>
            </form>

您应该在重置方法中传递一个带有表单字段值的对象。

reset({
  type: "contact",
  firstName: "John",
  lastName: "Doe"
})

如果您在 useForm 挂钩中设置默认初始值,调用 reset() 会导致表单字段设置为您的初始值,但如果您传递具有不同数据的对象,字段设置为您传递的值。

因此,在您的情况下,您应该在特定时刻保存表单状态,也许使用 getValues(),然后在单击按钮时设置您想要的值。

文档: Reset - React Hook Form

示例: Reset Example - Codesandbox