【问题标题】:How to use react-toastify promise in axios如何在 axios 中使用 react-toastify 承诺
【发布时间】:2022-07-16 12:28:23
【问题描述】:

// 我如何使用 toastify 的承诺,就像我想在获取数据时显示微调器然后消息成功或失败

// 但我在下面的代码中遇到错误

const fetch = () => {
    axios
      .get("https://restcountries.com/v2/name/india")
      .then((res) => {
        toast.promise({
          pending:"pending",
          success:"success",
          error:"rejected"
        } )
        console.log(res);
      })
      .catch((err) => {
        toast.error("???? failed", {
          position: "top-center",
          autoClose: 2000,
          hideProgressBar: true,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined
        });
      });
  };

【问题讨论】:

    标签: javascript reactjs axios react-toastify


    【解决方案1】:

    根据 toast API https://fkhadra.github.io/react-toastify/promise/ 的语法应该是

    const myPromise = fetchData();
    
    
    toast.promise(myPromise, {
       loading: 'Loading',
       success: 'Got the data',
       error: 'Error when fetching',
    })
    

    一个例子可以在https://codesandbox.io/s/twilight-bash-jzs24y?file=/src/App.js找到

     export default function App() {
            
            const myPromise = new Promise((resolve) =>
             fetch("https://jsonplaceholder.typicode.com/todos/1")
               .then((response) => response.json())
               .then((json) => setTimeout(() => resolve(json), 3000)) 
               // setTimeout just for the example , cause it will load quickly without it .
            );
    
           useEffect(() => {
             toast.promise(myPromise, {
                  pending: "Promise is pending",
                  success: "Promise  Loaded",
                  error: "error"
             });
           }, []);
    
           return (
                 <div className="App">
                      <ToastContainer />
                 </div>
           );
       }
    

    【讨论】:

      【解决方案2】:

      如果你没有使用承诺。使用toast.loading。 (文档:https://fkhadra.github.io/react-toastify/promise/#toastloading

      const getData = () => {
       const id = toast.loading("Please wait...")
       axios.get(`some-url`)
         .then(res => { 
            toast.update(id, {render: "All is good", type: "success", isLoading: false});
       }).catch(err => {
              toast.update(id, {render: "Something went wrong", type: "error", isLoading: false });
         });
      }
      

      如果它不起作用,则将 toast id 存储在 useRef 中,然后它就会起作用。

      【讨论】:

        猜你喜欢
        • 2018-02-14
        • 2020-03-19
        • 2018-09-19
        • 1970-01-01
        • 2019-03-11
        • 2018-02-06
        • 2022-01-22
        • 1970-01-01
        • 2018-03-05
        相关资源
        最近更新 更多