簡體   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