简体   繁体   English

如何防止提交表单后加载空白页?

[英]How to prevent loading blank page after submitting form?

I have an issue with reloading a blank page after submitting a contact form.我在提交联系表格后重新加载空白页面时遇到问题。 Contact form is working, email is sending to me but after that itself loading a blank page.联系表正在工作,email 正在发送给我,但之后它自己加载了一个空白页面。

I would prefer it to act like this: submiting a form -> sending an message -> clearing values -> without reloading.我希望它像这样:提交表单 -> 发送消息 -> 清除值 -> 无需重新加载。

So I know about e.preventDefault() I tried to use it but for it I need an additional funcion to pass e prop.所以我知道e.preventDefault()我尝试使用它但是为此我需要一个额外的函数来传递e prop。 For example: But I can't pass a hook into the function.例如:但我无法将钩子传递到 function。

  const handleSubmit (e: any) => {
    const [state, handleSubmit] = useForm('xwkjewea');
    e.preventDefault()
    if (state.succeeded) {
      formRef.current.resetFields();
      formRef.current.message.success('Wiadomość została wysłana');
    }
  }

I'm using FormSpree to service my message sending and for properly working it I needed to do it like below:我正在使用 FormSpree 来为我的消息发送提供服务,并且为了正常工作,我需要像下面这样进行操作:

const Contact = () => {
  const formRef = useRef<any>();
  const captchaRef = useRef<HCaptcha>(null);

  const [token, setToken] = useState<string>('');
  const [state, handleSubmit] = useForm('formSpree-id');

  if (state.succeeded) {
    formRef.current.resetFields();
    formRef.current.message.success('Sent');
  }

  const onExpire = () => {
    setToken('');
    message.warning('Expired');
  };

  const onError = (err: string) => {
    setToken('');
    message.error(`${err}`);
  };

  return (
    <Wrapper>
      <Title>Contact</Title>
      <MessageForm
        ref={formRef}
        name='nest-messages'
        onFinish={handleSubmit}
        validateMessages={validateMessages}
      >
    [...]

You can use the e.preventDefault() in a anonymous function and then pass the e event through to the handleSubmit function.您可以在匿名 function 中使用e.preventDefault() ,然后将e事件传递给handleSubmit function。

<MessageForm
  ref={formRef}
  name="nest-messages"
  onFinish={(e) => {
    e.preventDefault();
    handleSubmit(e);
  }}
  validateMessages={validateMessages}
>

I do recommend put the state.succeeded check in a useEffect to avoid clearing the form when other states change我确实建议将state.succeeded检查放在useEffect中,以避免在其他状态更改时清除表单

useEffect(() => {
  if (state.succeeded) {
    formRef.current.resetFields();
    formRef.current.message.success("Sent");
  }
}, [state.succeeded]);

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

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