You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在更新数据库前先在客户端UI中删除参与者(React技术栈)

实现客户端删除参与者并实时更新UI的方案

要实现提交前在客户端删除参与者的功能,核心是将参与者列表的状态交由react-hook-form管理,而非直接依赖TanstackQuery返回的原始数据。这样删除操作能实时更新表单状态,UI也会同步变化。具体实现步骤如下:

1. 修正表单初始化逻辑

确保react-hook-form能正确获取TanstackQuery返回的初始数据,在useForm中配置默认值,并在数据加载完成后填充表单:

const EditAppointment = ({ params }) => {
  const { id } = params;
  const appointment = useQuery({
    queryKey: ['appointment', 'data', 'history', id],
    queryFn: () => fetch(`/api/single-sched/${id}`).then((res) => res.json())
  });

  const { data } = appointment;

  const form = useForm<CreateAppointmentSchemaType>({
    resolver: zodResolver(CreateAppointmentSchema),
    defaultValues: {
      title: '',
      name_of_assistance: []
    }
  });

  // 数据加载完成后重置表单,填充初始值
  useEffect(() => {
    if (data) {
      form.reset({
        title: data.title,
        name_of_assistance: data.name_of_assistance || []
      });
    }
  }, [data, form]);

2. 编写删除函数,操作表单状态

使用react-hook-form的setValue方法,过滤掉要删除的参与者,更新表单中的name_of_assistance字段:

const removeAssistant = (targetName: string) => () => {
  const currentAssistants = form.getValues('name_of_assistance');
  const updatedAssistants = currentAssistants.filter(
    assistant => assistant.name !== targetName
  );
  form.setValue('name_of_assistance', updatedAssistants);
};

如果更倾向于用数组助手函数(代码更简洁),可以这样写:

const removeAssistant = (index: number) => () => {
  form.control.array('name_of_assistance').remove(index);
};

3. 调整UI渲染,基于表单状态展示列表

不再直接使用TanstackQuery的data,而是通过react-hook-form的watch方法获取当前表单中的参与者列表,确保删除后UI自动更新:

// 获取表单中当前的参与者列表
const currentAssistants = form.watch('name_of_assistance');

return (
  <Form {...form}>
    <form>
      <FormField
        control={form.control}
        name="title"
        render={({ field }) => (
          <FormItem>
            <FormLabel>Title</FormLabel>
            <FormControl>
              <Input {...field} />
            </FormControl>
          </FormItem>
        )}
      />

      <Table className='max-w-[400px]'>
        <TableHeader>
          <TableRow>
            <TableHead>Name</TableHead>
            <TableHead>Email</TableHead>
            <TableHead></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {/* 遍历表单维护的参与者列表 */}
          {currentAssistants.map((item, index) => (
            <TableRow key={item.name || index}>
              <TableCell>{item.name}</TableCell>
              <TableCell>{item.email}</TableCell>
              <TableCell>
                {/* 传递名称或索引到删除函数 */}
                <Button onClick={removeAssistant(item.name)} variant="destructive" size="icon">
                  <Trash2 />
                </Button>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>

      <Button type="submit">更新预约</Button>
    </form>
  </Form>
);
};

关键说明

  • 将参与者列表的状态从TanstackQuery原始数据转移到react-hook-form表单状态中,客户端操作可实时反映在UI上,提交时也能直接获取更新后的列表。
  • 使用form.reset初始化表单,确保异步获取的数据能正确填充到表单字段。
  • 删除操作直接修改表单字段值,react-hook-form会自动触发UI更新,无需手动管理额外状态。

内容的提问来源于stack exchange,提问作者Stykgwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 08:49:59