【问题标题】:How to use async onFinish method with Ant Design Form如何在 Ant Design Form 中使用 async onFinish 方法
【发布时间】:2020-06-09 05:25:15
【问题描述】:

当我在 onFinish 参数上设置异步函数时,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>'

如何实现异步函数?

我的代码是这样的。

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}>
      ・
      ・
      ・
);

【问题讨论】:

    标签: reactjs async-await antd


    【解决方案1】:

    onFinish 需要一个函数回调而不是 Promise。

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

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

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

    因此您可以使用 .then 功能而无需 async/await。

    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}>
          ・
          ・
          ・
    );
    

    【讨论】:

    • 感谢您的回答!!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2020-03-09
    • 2020-08-28
    • 2020-08-06
    • 2019-10-22
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多