将参数从一个箭头功能传递给另一个功能?

时间:2019-01-31 21:48:10

标签: javascript

我在Reactjs中使用formik,并且有一个onSubmit方法,该方法具有setSubmitting参数。我想将其传递给我的“ then”方法,但不确定如何执行。

  onSubmit={(values, { setSubmitting, setErrors }) => {

            setSubmitting(true);

            // how can I get away from doing this.
            const submitting = setSubmitting;

              ajaxMethod(values)
              .then(() => {
                submitting(false);  // how could I just call setSubmitting.             
              })
              .catch((error, ) => {

                submitting(false);
              });
          }}

编辑

 <Formik
          initialValues={{
          }}
          validationSchema={Yup.object().shape({
          })}
          onSubmit={(values, { setSubmitting, setErrors }) => {
            setSubmitting(true);

            const submitting = setSubmitting;

            ajaxMethod(values)
              .then(() => {
                setSubmitting(false);
              })
              .catch((error, setSubmitting) => {
                setSubmitting(false);
              });
          }}
          render={props => (
            <Form autoComplete="off" id="record-payment-form">

            </Form>
          )}
        />


 ajaxMethod: flow(function*(formData) {

    })

1 个答案:

答案 0 :(得分:1)

您根本不需要该本地submitting变量。只需致电setSubmitting

(values, { setSubmitting, setErrors }) => {
    setSubmitting(true);

    ajaxMethod(values).then(() => {
        setSubmitting(false);
    }).catch((error) => {
        setSubmitting(false);
    });
}

顺便说一句,您可能想改用finally

(values, { setSubmitting, setErrors }) => {
    setSubmitting(true);

    ajaxMethod(values).finally(() => {
        setSubmitting(false);
    });
}