繁体   English   中英

提交成功或失败后如何在反应表单中显示 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} />
        </>
    );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM