0

// 想在发布时显示微调器,然后使用 react-toastify 显示成功/错误消息是否可能?

axios.post("/orders.json", order)
      .then((response) => {
        console.log(response.status);
      })
      .catch((error) => {
        console.log(error);
      });
4

2 回答 2

0

这将解决您的问题。

import React, { useEffect, useState } from "react";
import axios from "axios";
import { toast } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
toast.configure({
    position: toast.POSITION.BOTTOM_RIGHT
});

export default function App() {
    const [state, setState] = useState({
        loading: true,
        dataArray: []
    });

    const myRequest = async () => {
        try {
            const request = await axios.get(`/generic_data/search_skills`);
            const { error, msg, data } = request.data;
            if (error) throw new Error(msg);
            setState({ ...state, loading: false, dataArray: data });
            toast.success("All good, we have the data");
        } catch (e) {
            toast.error("Upps, someting went wrong");
        }
  };
  
  useEffect(()=>{
    myRequest()
  },[])

    if (state.loading) {
        return "Loading data from server.. this will take long time...";
    }

    return <div>The request has ended. We have the data</div>;
}
于 2022-03-04T05:16:23.813 回答
0

对的,这是可能的。您可以调用一个状态isLoading,并且可以true在提交请求时将其设置为,并且可以在渲染组件之前post进行检查,如下所示。isLoading

 if(isLoading) {
     return (<Spinner />)
 }

您可以在方法执行后使用 toast 显示success/error消息。post像下面

 toast.error('Sorry request failed')

或者

 toast.success('Request successfull')

但在使用 toast 之前,您已经将App组件包装在toast container如下所示。

 import React from 'react';

 import { ToastContainer, toast } from 'react-toastify';
 import 'react-toastify/dist/ReactToastify.css';

 function App(){
    const notify = () => toast("Wow so easy!");

    return (
       <div>
          <button onClick={notify}>Notify!</button>
          <ToastContainer />
       </div>
    );
  }
于 2022-03-04T05:05:51.047 回答