簡體   English   中英

返回語句給出未定義

[英]Return statement giving undefined

我有一個 function: fetchAll ,它在fetch.js文件中。

import axios from "../axios";

export default function fetchAll() {
  axios.get("/api/videos/all").then((response) => {
    return response.data;
  });
}

然后在Home.js中:

import fetchAll from "../functions/fetch";


 useEffect(() => {
  var videos = fetchAll();
  console.log(videos);
 },[])

但是 function 返回undefined而不是數據。
任何幫助是極大的贊賞 !

問題

您沒有從fetchAll function 返回任何內容。

export default function fetchAll() {
  axios.get("/api/videos/all").then((response) => {
    return response.data;
  });
  // <-- no return, void return
}

解決方案

從 axios 返回axios

export default function fetchAll() {
  return axios.get("/api/videos/all").then((response) => {
    return response.data;
  });
}

當然,您需要等待 Promise 在useEffect回調中解析。

useEffect(() => {
  const getFetchAll = async () => {
    try {
      const videos = await fetchAll();
      console.log(videos);
    } catch(err) {
      console.error(err);
    }
  }

  getFetchAll();
},[]);

暫無
暫無

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

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