[英]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.