提交成功或失败后如何在反应表单中显示 toastr 警报?
How to display a toastr alert in a react form after submit succeed or failed?
我想知道如何在点击“发送信息”按钮显示“您的信息已发送”时显示toastr警报,如果失败“您的信息无法发送,这里有问题!”
我要发送的代码是:
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} />
</>
);
};
我想知道如何在点击“发送信息”按钮显示“您的信息已发送”时显示toastr警报,如果失败“您的信息无法发送,这里有问题!”
我要发送的代码是:
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} />
</>
);
};