调用API后如何更新默认值?
这就是我想要实现的目标:
现在假设我已经留下了评论
Comment test 1
,因此当渲染卡片时,它将使用defaultValues
的注入数据显示评论。我将注释编辑为Comment test 2
,然后单击保存,现在显示的注释来自状态值,而不是来自默认值。现在我想编辑到Comment Test 3
,但我改变了主意并放弃了更改。现在卡片将显示默认值 Comment Test 1
,而它应该显示 Comment Test 2
。
所以我想有一种方法可以在调用API后更新defaultValues,我已经尝试成功使用
resetField('comment', { defaultValue: { ...comment } });
,但是默认评论没有更新。
解决问题的更好方法是什么?
您可以做的是将保存的值存储在变量中(例如
overwrittenForm
),然后使用 useForm 挂钩中的 formContext.reset(overwrittenForm)
并将其传递给变量以重置为最新状态。
您是否尝试过在 defaultValue 中使用异步,如下所示?
...
const form = useForm<z.infer<typeof InfoSchema>>({
resolver: zodResolver(InfoSchema),
defaultValues: async () => {
const { data } = await getDataFromApi()
return {
item1: data?.item1 as string ?? undefined,
comment1: data?.comment2 as string ?? undefined,
}
},
});
...