提交成功或失败后,如何在反应表单中显示祝酒词警报



我想知道如何在单击";发送信息";按钮显示";您的信息已发送";如果失败;您的信息无法发送,出现问题">

我要发送的代码是:

const sendMail = async (data: FormData) => {
const response = await fetch('https://us-central1-my-website.cloudfunctions.net/apply-function', {
method: 'POST',
body: data,
});
};

一旦解析或拒绝,response对象将具有一个名为status的属性,该属性指示请求是被服务器(API(解析还是拒绝。您可以使用status属性来相应地显示警报。

示例

import React from 'react';
const Mail = () => {
const [alert, setAlert] = React.useState({ show: false, message: '' });
const sendMail = async (data: FormData) => {
//  It's better to use try catch block when writing an async function.
try {
const response = await fetch(
'https://us-central1-my-website.cloudfunctions.net/apply-function',
{
method: 'POST',
body: data,
}
);
if (response.status === 200) {
setAlert({
show: true,
message: 'Your information has been sent!',
});
}
} catch {
// If response was not successful.
setAlert({
show: true,
message: 'Your information could not be sent!',
});
}
};
return (
<>
{/* Other components.. */}
<Toaster show={alert.show} message={alert.message} />
</>
);
};

最新更新