Reactjs:formsubmit.co 不会重定向到它的页面

问题描述 投票:0回答:1
const InputPhone = (props) => {
    const {control} = useForm();
    const [telValue, setTelValue] = useState('');

    const handleSubmit = async () => {
        const emailData = {
            attachment: 'Order recieved',
            html: telValue
        };

        try {
            const response = await axios.post('https://formsubmit.co/el/cimewa', emailData);
            console.log('Email sent:', response.data);
        } catch (error) {
            console.error('Email error:', error);
        }
    };
<Btn click={handleSubmit}>Order</Btn>
const Input = () => {
    const {control, formState: {errors}, handleSubmit} = useForm()
    const onSubmit = (data) => {
        alert(JSON.stringify(data))
    }

    return (
        <div>
            <form onSubmit={handleSubmit(onSubmit)} className={cl.form} method='post'>

按下按钮时没有任何反应。但如果我在 formsubmit.co 网站上使用测试表单 - 它会重定向我。 如何解决这个问题? 即使使用 Chatgpt 也无法修复它。它对我说一切都好,或者生成与我使用的相同的代码。 谢谢!

javascript reactjs redirect form-submit contact-form
1个回答
0
投票

formsubmit.co
中,表单通过 POST 操作
<form method="post" url="destination_url">
提交,该操作将重定向到
destination_url
。这是 HTML 表单元素的默认提交行为。在 React 中,当您使用
react-hook-form
时,
handleSubmit
函数现在是提交事件处理程序,它是库实现的自定义处理程序。它不重定向你的原因是它是这样实现的

const handleSubmit = (submitCallback) => (e) => {
  e.preventDefault(); // prevent redirecting to destination_url
  // other extra code
}

现在,如果您想将用户重定向到任何端点,只需修改提交回调中的 trycatch 块

try {
  const response = await axios.post('https://formsubmit.co/el/cimewa', emailData);
  console.log('Email sent:', response.data);
  window.location = 'destination_url' // redirect with window.location if this destination_url is an external URL
  // or use navigate of react-router-dom if it is an internal URL of your app 
} catch (error) {
  console.error('Email error:', error);
}

希望这能有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.