reactjs - 在 react 中提交表单后重定向到网站

标签 reactjs create-react-app

我知道这个问题已经被问了一百万次,尽管我仍然很难将答案转移到我的案例中。对于更有经验的人来说,答案可能是微不足道的。我对 react 非常陌生。我想在表单成功提交后重定向到“/”。我尝试相应地修改handleSubmit,但我的所有尝试都没有成功。问题是用户不知道消息已经发送并且提交后消息仍然在表单中。所以,我只想重定向到根目录。

这是我的组件:


import React from "react";
import { ChatIcon } from "@heroicons/react/solid";
import { useHistory } from "react-router-dom";

export default function Contact() {
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [message, setMessage] = React.useState("");
  const history = useHistory() 
  
  function encode(data) {
    return Object.keys(data)
      .map(
        (key) => encodeURIComponent(key) + "=" + encodeURIComponent(data[key])
      )
      .join("&");
  }

  function handleSubmit(e) {
    e.preventDefault();
    fetch("/", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: encode({ "form-name": "contact", name, email, message }),
    })
      .then(() => {
        console.log('Email sent');
        history.push('/');
      })
      .catch((error) => console.log(error));
  }

  return (
    <section id="contact" className="relative">
      <div className="container px-5 pt-20 pb-0 mx-auto text-center">
      <ChatIcon className="w-10 inline-block mb-4" />

        <h1 className="sm:text-4xl text-3xl font-medium title-font text-white mb-4">
              Get in touch
        </h1>
        <p className="text-base leading-relaxed xl:w-2/4 lg:w-3/4 mx-auto">
            You have ideas about collaborations or questions about my latest projects? Feel free to reach out!<br/> I am happy to talk. 
        </p>        
      </div>
      <div className="container px-5 pb-10 mx-auto flex sm:flex-nowrap flex-wrap">
        <form
          netlify
          data-netlify-recaptcha="true"
          data-netlify="true"
          netlify-honeypot="bot-field"
          name="contact"
          onSubmit={handleSubmit}
          className="lg:w-1/3 md:w-1/2 flex flex-col md:ml-auto w-full md:py-8 mt-8 md:mt-0">
          
          <input type="hidden" name="form-name" value="contact" />

          <div className="relative mb-4">
            <label htmlFor="name" className="leading-7 text-sm text-gray-400">
              Name
            </label>
            <input
              type="text"
              id="name"
              name="name"
              className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <div className="relative mb-4">
            <label htmlFor="email" className="leading-7 text-sm text-gray-400">
              Email
            </label>
            <input
              type="email"
              id="email"
              name="email"
              className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          <div className="relative mb-4">
            <label
              htmlFor="message"
              className="leading-7 text-sm text-gray-400">
              Message
            </label>
            <textarea
              id="message"
              name="message"
              className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 h-32 text-base outline-none text-gray-100 py-1 px-3 resize-none leading-6 transition-colors duration-200 ease-in-out"
              onChange={(e) => setMessage(e.target.value)}
            />
          </div>
          <div data-netlify-recaptcha="true" class="form-row"></div>
          <button
            type="submit"
            className="text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded text-lg">
            Submit
          </button>
        </form>

        <div className="lg:w-2/3 md:w-1/2 bg-gray-900 rounded-lg overflow-hidden sm:ml-10 p-10 flex items-end justify-start relative mt-10">
          <iframe
            width="100%"
            height="100%"
            title="map"
            className="absolute inset-0"
            frameBorder={0}
            marginHeight={0}
            marginWidth={0}
            style={{ filter: "opacity(0.7)" }}
            src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d109162.25531026715!2d-114.16629014851806!3d51.041178754239546!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x53717db7481cb3b1%3A0x36aff4a9e3c803fb!2sUniversity%20of%20Calgary!5e0!3m2!1sen!2sca!4v1629156439590!5m2!1sen!2sca"
          />
          <div className="bg-gray-900 relative flex flex-wrap py-6 rounded shadow-md">
            <div className="lg:w-1/2 px-6">
              <h2 className="title-font font-semibold text-white tracking-widest text-xs">
                ADDRESS
              </h2>
              <p className="mt-1">
                2500 University Dr NW, T2N 1N4, Calgary, AB, Canada
              </p>
            </div>
            <div className="lg:w-1/2 px-6 mt-4 lg:mt-0">
              <h2 className="title-font font-semibold text-white tracking-widest text-xs">
                EMAIL
              </h2>
              <a className="text-indigo-400 leading-relaxed" href='mailto:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1c2c6d0d2dad4c3f1c4d2d0ddd6d0c3c89fd2d0" rel="noreferrer noopener nofollow">[email protected]</a>'>
                <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfccc8dedcd4dacdffcadcded3d8decdc691dcde" rel="noreferrer noopener nofollow">[email protected]</a>
              </a>
              <h2 className="title-font font-semibold text-white tracking-widest text-xs mt-4">
                LINKED IN
              </h2>
              <p className="leading-relaxed"><a href='https://www.linkedin.com/in/sorenwacker/'>sorenwacker</a>   </p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

我找到了使用浏览器历史记录、Redirectredirect 变量的解决方案。 不过,我不确定什么是最好的方法。

最佳答案

react-router-dom中,您可以导入钩子(Hook)useHistory。然后做这样的事情:

const history = useHistory();

const handleSubmit = (e) => {
    // your submit logic ...

    history.push("/");
}

关于reactjs - 在 react 中提交表单后重定向到网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68854481/

相关文章:

javascript - 状态更改时子组件的 props 不会更新

java - Corda RPC : A hot observable returned from an RPC was never subscribed to

reactjs - 如何根据当前 url/url 片段呈现不同的消息

node.js - 要导入Sass文件,首先需要安装node-sass

javascript - React - Internet Explorer 11 输入在第一次 onchange 后失去焦点

javascript - 发布的 github 页面上出现 "Failed to create temp file 18"错误

reactjs - "npm start"如何在 create-react-apps 中工作

javascript - 如何获取d3.js Treemap布局中元素的对象属性onclick

reactjs - 如何在 App.js 中没有函数的情况下创建 React.js 应用程序

javascript - 如何在 react 路由器中将子路由定义为 react 组件?