在提交之前,使用Formik重置表單
P粉138711794
P粉138711794 2023-09-10 22:06:21
0
1
574

點擊提交按鈕後,在提交之前會重置表單。

我使用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>在这里添加图片</p>
                                ) : (
                                    values.picture.name
                                )}
                            </div>
                        )}
                    </Dropzone>
                    <button type="submit" onClick={resetForm}>提交</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);
            });
    };
P粉138711794
P粉138711794

全部回覆(1)
P粉592085423

刪除 onClick={resetForm} :

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

然後在你的 handleFormSubmit 中:

...

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

如果對你有用,請告訴我。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板