React中Emailjs表单提交后出现404错误,如何重定向或弹出模态框?
解决React Emailjs表单提交后404/重定向及自定义模态框问题
问题原因
你当前代码里的window.location.reload(false)会刷新当前页面,再加上form标签的action=''是空值,导致浏览器刷新后找不到对应路由,跳转到404页面。下面给两种解决方案:
方案一:提交成功后重定向到首页
方式1:React Router跳转(单页应用推荐)
如果你的项目用了react-router-dom,直接用useNavigate钩子实现路由跳转,不需要刷新页面:
import { useNavigate } from 'react-router-dom'; const YourFormComponent = () => { const form = useRef(); const navigate = useNavigate(); const sendEmail = (e) => { e.preventDefault(); emailjs.sendForm('sensitiveinfo', 'sensitiveinfo', form.current, 'sensitiveinfo') .then( () => { alert('Message successfully sent!'); navigate('/'); // 跳转到首页路由 }, () => { alert('Failed to send the message, please try again'); } ); }; return ( <form ref={form} onSubmit={sendEmail}> {/* 你的表单内容 */} <input className='submit' type="submit" value="Send" /> </form> ); };
方式2:原生JS跳转(无路由场景)
如果没使用React Router,直接修改页面地址跳转,同时记得删掉form标签的action=''属性:
const sendEmail = (e) => { e.preventDefault(); emailjs.sendForm('sensitiveinfo', 'sensitiveinfo', form.current, 'sensitiveinfo') .then( () => { alert('Message successfully sent!'); window.location.href = '/'; // 替换为你的首页路径 }, () => { alert('Failed to send the message, please try again'); } ); };
方案二:自定义带站内链接的模态框(体验更优)
原生alert交互性差,自己实现模态框可以灵活添加站内链接,用React状态控制显示隐藏即可:
import { useState, useRef } from 'react'; import { Link } from 'react-router-dom'; // 用路由的话导入Link const YourFormComponent = () => { const form = useRef(); const [showModal, setShowModal] = useState(false); const [isSuccess, setIsSuccess] = useState(false); const sendEmail = (e) => { e.preventDefault(); emailjs.sendForm('sensitiveinfo', 'sensitiveinfo', form.current, 'sensitiveinfo') .then( () => { setIsSuccess(true); setShowModal(true); form.current.reset(); // 可选:清空表单 }, () => { setIsSuccess(false); setShowModal(true); } ); }; return ( <> <form ref={form} onSubmit={sendEmail}> {/* 你的表单内容 */} <input className='submit' type="submit" value="Send" /> </form> {/* 自定义模态框 */} {showModal && ( <div style={{ position: 'fixed', top: 0, left: 0, width: '100vw', height: '100vh', backgroundColor: 'rgba(0,0,0,0.6)', display: 'flex', justifyContent: 'center', alignItems: 'center', zIndex: 999 }}> <div style={{ backgroundColor: '#fff', padding: '24px', borderRadius: '8px', maxWidth: '400px', textAlign: 'center' }}> {isSuccess ? ( <> <h3>消息发送成功!</h3> <p>可以看看这些页面:</p> <div style={{ marginTop: '16px', display: 'flex', gap: '16px', justifyContent: 'center' }}> <Link to="/">返回首页</Link> <Link to="/about">关于我们</Link> <Link to="/services">服务介绍</Link> </div> </> ) : ( <h3>发送失败,请稍后重试!</h3> )} <button onClick={() => setShowModal(false)} style={{ marginTop: '20px', padding: '8px 16px', cursor: 'pointer' }} > 关闭 </button> </div> </div> )} </> ); };
你可以根据项目的样式规范调整模态框的CSS,完全自定义内容和交互。
内容的提问来源于stack exchange,提问作者solodolo94
相关产品推荐
相关产品推荐

