提交时清除Formik表格不起作用,我在做什么错?

时间:2019-11-18 14:49:46

标签: reactjs axios formik

我正在尝试寻找一种在提交时清除此表单的方法,我尝试过的任何方法都无济于事。对于我做错了什么,我将不胜感激!

我尝试添加重置和onClick事件以将数据设置回初始值,但我似乎无济于事。

FormJr.js

import React from "react";
import { useFormik } from "formik";
import axios from "axios";
const Form = ({ load, setLoad }) => {
  const formik = useFormik({
    initialValues: {
      name: "",
      date: "",
      comment: ""
    },
    onSubmit: values => {
      setLoad(load !== true ? true : false);
      axios
        .post(`https://lq-time-tracking.firebaseio.com/${name}.json`, values)
        .then(function(response) {})
        .catch(function(error) {
          console.log(error);
        });
    }
  });
  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="name">Name</label>
      <select
        id="name"
        name="name"
        type="name"
        onChange={formik.handleChange}
        value={formik.values.name}
      >
        <option value=""> Select One...</option>
        <option value="Ryan">Ryan</option>
        <option value="Patrick">Patrick</option>
        <option value="Jennifer">Jennifer</option>
        <option value="Dan">Dan</option>
      </select>
      <label htmlFor="date">Date</label>
      <input
        id="date"
        name="date"
        type="date"
        onChange={formik.handleChange}
        value={formik.values.date}
      />
      <label htmlFor="comment">Comment</label>
      <input
        id="comment"
        name="comment"
        type="comment"
        onChange={formik.handleChange}
        value={formik.values.comment}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default Form;

1 个答案:

答案 0 :(得分:1)

在您的formik.resetForm()中尝试onSubmit()

const formik = useFormik({
    initialValues: {
      name: "",
      date: "",
      comment: ""
    },
    onSubmit: values => {
      formik.resetForm()
    }
  });