简体   繁体   English

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

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

When I set an async function on onFinish param, VSCode says the warning message below当我在 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>'

How can I implement an async function?如何实现异步 function?

My code is like this.我的代码是这样的。

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 requires a function callback instead of Promise. onFinish 需要 function 回调而不是 Promise。

You can use the arrow function.您可以使用箭头 function。 But don't forget to use Promise actions in it if you need it.但是,如果需要,请不要忘记在其中使用 Promise 操作。

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

Since you don't have any Promise logic in your onFinish function it doesn't make sense to use async/await in it.由于您的 onFinish function 中没有任何 Promise 逻辑,因此在其中使用 async/await 是没有意义的。

So you could use.then functionality without 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