【问题标题】:How to display a toastr alert in a react form after submit succeed or failed?提交成功或失败后如何在反应表单中显示 toastr 警报?
【发布时间】:2020-10-16 16:12:41
【问题描述】:
我想知道如何在单击显示“您的信息已发送”的“发送信息”按钮时显示一个 toastr 警报,如果失败则“您的信息无法发送,这里有问题!”
我发送的代码是:
const sendMail = async (data: FormData) => {
const response = await fetch('https://us-central1-my-website.cloudfunctions.net/apply-function', {
method: 'POST',
body: data,
});
};
【问题讨论】:
标签:
javascript
reactjs
forms
react-redux
toastr
【解决方案1】:
一旦解决或拒绝,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} />
</>
);
};