简体   繁体   English

提交后重置表格

[英]Reset Form After Submitting

I have a react form that calls a graphql mutation when the button is clicked.我有一个反应表单,在单击按钮时调用 graphql 突变。 After the button is clicked and the mutation is completed, the text in the form is still there.点击按钮完成变异后,表单中的文字还在。 So in order to run a new mutation, the user will have to manually remove the text written in the text fields.因此,为了运行新的突变,用户必须手动删除文本字段中写入的文本。

Is there any way to automatically reset the text fields once the form is submitted?提交表单后,有什么方法可以自动重置文本字段?

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const [removeUser] = useMutation<DeleteUserReponse>(REMOVE_USER);

  let submitForm = (email: string) => {
    setIsSubmitted(true);
    removeUser({
      variables: {
        email: email,
      },
    })
      .then(({ data }: ExecutionResult<DeleteUserReponse>) => {
        if (data !== null && data !== undefined){
        setIsRemoved(true);
      }})
      .catch((error: { message: string }) => {
        setIsRemoved(false);
        setErrorMessage(error.message);
      });
  };

  const initialValues={ email: '' }
  return (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        //initialValues={{ email: '' }}
        initialValues={initialValues}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
          initialValues={initialValues}
        }}
        validationSchema={schema}>
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched,
          } = props;
          const change = (name: string, e: FormEvent) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
          };
          return (
            <div>
              <form
                style={{ width: '100%' }}
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </form>
              {isSubmitted && StatusMessage(isRemoved, errorMessage)}
            </div>
          );
        }}
      </Formik>
    </div>
  );
}

Try reusing your initial state, something like this:尝试重用您的初始 state,如下所示:

const INITIAL_STATE = { email: '' };

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const [removeUser] = useMutation<DeleteUserReponse>(REMOVE_USER);

  let submitForm = (email: string) => {
    setIsSubmitted(true);
    removeUser({
      variables: {
        email: email,
      },
    })
      .then(({ data }: ExecutionResult<DeleteUserReponse>) => {
        if (data !== null && data !== undefined){
        setIsRemoved(true);
      }})
      .catch((error: { message: string }) => {
        setIsRemoved(false);
        setErrorMessage(error.message);
      });
  };

  return (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        initialValues={{ ...INITIAL_STATE }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
          actions.setValues({ ...INITIAL_STATE });
        }}
        validationSchema={schema}>
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched,
          } = props;
          const change = (name: string, e: FormEvent) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
          };
          return (
            <div>
              <form
                style={{ width: '100%' }}
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ''}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, 'email')}
                  />
                  <CustomButton
                    disabled={!isValid || !email}
                    text={'Remove User'}
                  />
                </div>
              </form>
              {isSubmitted && StatusMessage(isRemoved, errorMessage)}
            </div>
          );
        }}
      </Formik>
    </div>
  );
}

Although I've also seen resetForm method on second parameter of onSubmit , but haven't tested it how it works, so you can try that also.虽然我在onSubmit的第二个参数上也看到resetForm方法,但还没有测试它是如何工作的,所以你也可以试试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM