繁体   English   中英

如何在 Ant 设计表单中使用 async onFinish 方法

[英]How to use async onFinish method with Ant Design Form

当我在 onFinish 参数上设置异步 function 时,VSCode 会显示以下警告消息

(JSX attribute) onFinish?: ((values: Store) => void) | undefined
Type '(values: NannyProfileUpdateType) => Promise<void>' is not assignable to type '(values: Store) => void'.
  Types of parameters 'values' and 'values' are incompatible.
    Type 'Store' is missing the following properties from type 'NannyProfileUpdateType': firstName, lastName, email, doesStartASA, and 32 more.ts(2322)
Form.d.ts(15, 5): The expected type comes from property 'onFinish' which is declared here on type 'IntrinsicAttributes & FormProps & RefAttributes<FormInstance>'

如何实现异步 function?

我的代码是这样的。

const onFinish = async (values) => {
  setIsSubmitting(true);
  const response = await Api.get(worker.id as number);
  setWorker(response.worker);
  openSnackbar();
  setIsSubmitting(false);
};


return (
  <Form
    layout="vertical"
    hideRequiredMark
    onFinish={onFinish}
    initialValues={worker}
  >
    <Row gutter={16}>
      <Col span={12}>
      ・
      ・
      ・
);

onFinish 需要 function 回调而不是 Promise。

您可以使用箭头 function。 但是,如果需要,请不要忘记在其中使用 Promise 操作。

<Form
    layout="vertical"
    hideRequiredMark
    onFinish={(values) => onFinish(values)}
    initialValues={worker}
  >

由于您的 onFinish function 中没有任何 Promise 逻辑,因此在其中使用 async/await 是没有意义的。

所以你可以在没有 async/await 的情况下使用.then 功能。

const onFinish = (values) => {
  setIsSubmitting(true);
  Api.get(worker.id as number)
     .then(response => {
       setWorker(response.worker);
       openSnackbar();
     })
     .catch((error) => setError(error))
     .finally(() => {
       setIsSubmitting(false);
     });
};


return (
  <Form
    layout="vertical"
    hideRequiredMark
    onFinish={onFinish}
    initialValues={worker}
  >
    <Row gutter={16}>
      <Col span={12}>
      ・
      ・
      ・
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM