Formik 在提交之前重置表单。

huangapple go评论97阅读模式
英文:

Formik resets form before submit

问题

当单击提交按钮时,在提交之前表单会被重置。

我使用Formik创建了一个表单。我尝试在提交后使用Formik的resetForm来重置表单。但它在提交之前重置了表单并提交了一个空表单。以下是我的表单:

<Formik
  onSubmit={handleFormSubmit}
  initialValues={{
    content: "",
    picture: "",
  }}
>
  {({
    values,
    handleBlur,
    handleChange,
    handleSubmit,
    setFieldValue,
    resetForm,
  }) => (
    <form onSubmit={handleSubmit}>
      <Field
        as="textarea"
        onBlur={handleBlur}
        onChange={handleChange}
        value={values.content}
        name="content"
      />

      <Dropzone
        acceptedFiles=".jpg, .jpeg, .png"
        multiple={false}
        onDrop={(acceptedFiles) => {
          setFieldValue("picture", acceptedFiles[0]);
        }}
      >
        {({ getRootProps, getInputProps }) => (
          <div {...getRootProps()}>
            <input {...getInputProps} />
            {!values.picture ? (
              <p>Add Picture Here</p>
            ) : (
              values.picture.name
            )}
          </div>
        )}
      </Dropzone>
      <button type="submit">提交</button>
    </form>
  )}
</Formik>

我不确定是否应该分享handleFormSubmit函数,但这里是它的代码:

const handleFormSubmit = async (values, onSubmitProps) => {
  const formData = new FormData();
  for (let value in values) {
    formData.append(value, values[value]);
  }
  formData.append("picturePath", values.picture.name);
  fetch(`http://localhost:5000/api/home-profile/${data[0]._id}`, {
    method: "PUT",
    body: formData,
    headers: {
      Authorization: "Bearer " + token,
    },
  })
    .then((res) => {
      console.log(res.status);
    })
    .catch((err) => {
      console.log(err);
    });
};
英文:

When clicked on submit button, form gets reseted before submited.

I have a form created with Formik. I'm trying to reset the form after submit with resetForm from Formik. But it resets the form before submitting it and submits an empty form. Here's my form:

&lt;Formik
			onSubmit={handleFormSubmit}
			initialValues={{
				content: &quot;&quot;,
				picture: &quot;&quot;,
			}}
		&gt;
			{({
				values,
				handleBlur,
				handleChange,
				handleSubmit,
				setFieldValue,
				resetForm,
			}) =&gt; (
				&lt;form onSubmit={handleSubmit}&gt;
					&lt;Field
						as=&quot;textarea&quot;
						onBlur={handleBlur}
						onChange={handleChange}
						value={values.content}
						name=&quot;content&quot;
					/&gt;

					&lt;Dropzone
						acceptedFiles=&quot;.jpg, .jpeg, .png&quot;
						multiple={false}
						onDrop={(acceptedFiles) =&gt;
							setFieldValue(&quot;picture&quot;, acceptedFiles[0])
						}
					&gt;
						{({ getRootProps, getInputProps }) =&gt; (
							&lt;div {...getRootProps()}&gt;
								&lt;input {...getInputProps} /&gt;
								{!values.picture ? (
									&lt;p&gt;Add Picture Herse&lt;/p&gt;
								) : (
									values.picture.name
								)}
							&lt;/div&gt;
						)}
					&lt;/Dropzone&gt;
					&lt;button type=&quot;submit&quot; onClick={resetForm}&gt; g&#246;nder&lt;/button&gt;
				&lt;/form&gt;
			)}
		&lt;/Formik&gt;

I'm not sure if I should share the handleFormSubmit function but here it is:

const handleFormSubmit = async (values, onSubmitProps) =&gt; {
		const formData = new FormData();
		for (let value in values) {
			formData.append(value, values[value]);
		}
		formData.append(&quot;picturePath&quot;, values.picture.name);
		fetch(`http://localhost:5000/api/home-profile/${data[0]._id}`, {
			method: &quot;PUT&quot;,
			body: formData,
			headers: {
				Authorization: &quot;Bearer &quot; + token,
			},
		})
			.then((res) =&gt; {
				console.log(res.status);
			})
			.catch((err) =&gt; {
				console.log(err);
			});
	};

答案1

得分: 2

从你的代码中移除 onClick={resetForm}:

<button type="submit">gönder</button>

然后在你的 handleFormSubmit 中:

.then((res) => {
    console.log(res.status);
})
.catch((err) => {
    console.log(err);
})
.finally(() => {
    resetForm(); // 这部分
});

如果对你有帮助,请告诉我。

英文:

Remove onClick={resetForm} :

&lt;button type=&quot;submit&quot;&gt; g&#246;nder&lt;/button&gt;

Then in your handleFormSubmit:

...

.then((res) =&gt; {
    console.log(res.status);
})
.catch((err) =&gt; {
    console.log(err);
})
.finally(() =&gt; {
    resetForm(); //this
});

Let me know if it works for you

huangapple
  • 本文由 发表于 2023年5月31日 22:50:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76374779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定