簡體   English   中英

使用 Axios 時如何解決 async-await 函數問題?

[英]How to solve async-await function problem while using Axios?

我想通過 async await 函數來使用 axios。

但是當我使用 async await 函數時,我得到一個錯誤。

useEffect(async() => {
   await axios
        .get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
        .then((data) => setItems(data.data));
}, []);

你同時使用了 Promise 和 async/await,要么使用.then()要么使用 async/await:這里我展示了如何使用 Promise 來做到這一點:

useEffect(async() => {
axios.get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
  .then(function (response) {
    setItems(response.data);
  })
  .catch(function (error) {
    console.log(error);
  })}, [])

這里我使用異步等待:

useEffect(async() => {
    let response = await axios.get("https://cryptic-inlet- 
    27003.herokuapp.com/products?size=6")
    setItems(response.data);
}, [])

問題是您同時使用 Promise 和 async/await。 Async/await 只不過是承諾的糖衣。 你可以在這里閱讀更多關於 Promise 的信息。

const fetchData = async () => {
  const { data } = await axios.get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
   // do something with data!
};
useEffect(async() => {
  fetchData();
}, []);

您不能在 useEffect 中使用異步等待,因為這不是反應的方法,您可以將邏輯代碼更改為其他代碼,例如使用useState 變量,並且使用 axios 的結果,您將更新useState 變量,例如那:

const [items, setItems]=useState({})//any

useEffect(async() => {
   axios
        .get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
        .then((data) => setItems(data.data));
}, []);

useEffect(()=>{
  console.log(items, 'this items changed')
  //to do...
}, [items])

或者

const [items, setItems]=useState({})//any

async function requestAxios(){
  const data=await axios.get("https://cryptic-inlet-27003.herokuapp.com/products?size=6")
  setItems(data.data)
}

useEffect(async() => {
   requestAxios()
}, []);

useEffect(()=>{
  console.log(items, 'this items changed')
  //to do...
}, [items])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM