Javascript 提交成功或失败后,如何在react表单中显示toastr警报?
我想知道当点击“发送信息”按钮显示“您的信息已发送”时,如何显示toastr警报,如果失败,“您的信息无法发送,这是一个问题!” 我发送的代码是:Javascript 提交成功或失败后,如何在react表单中显示toastr警报?,javascript,reactjs,forms,react-redux,toastr,Javascript,Reactjs,Forms,React Redux,Toastr,我想知道当点击“发送信息”按钮显示“您的信息已发送”时,如何显示toastr警报,如果失败,“您的信息无法发送,这是一个问题!” 我发送的代码是: const sendMail = async (data: FormData) => { const response = await fetch('https://us-central1-my-website.cloudfunctions.net/apply-function', { method: 'POST',
const sendMail = async (data: FormData) => {
const response = await fetch('https://us-central1-my-website.cloudfunctions.net/apply-function', {
method: 'POST',
body: data,
});
};
解析或拒绝后,
响应
对象将具有一个名为状态
的属性,该属性指示服务器(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} />
</>
);
};
从“React”导入React;
常量邮件=()=>{
const[alert,setAlert]=React.useState({show:false,消息:“”});
const sendMail=async(数据:FormData)=>{
//编写异步函数时最好使用try-catch块。
试一试{
const response=等待获取(
'https://us-central1-my-website.cloudfunctions.net/apply-function',
{
方法:“POST”,
正文:数据,
}
);
如果(response.status==200){
设置警报({
秀:没错,
消息:“您的信息已发送!”,
});
}
}抓住{
//如果响应不成功。
设置警报({
秀:没错,
消息:“无法发送您的信息!”,
});
}
};
返回(
{/*其他组件..*/}
);
};