我有一个函数: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);
},[])
但是函数返回的是 undefined
而不是数据。
非常感谢任何帮助!
答案 0 :(得分:3)
您没有从 module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: {
'@exmpl/(.*)': '<rootDir>/src/$1'
}
};
函数返回任何内容。
fetchAll
从export default function fetchAll() {
axios.get("/api/videos/all").then((response) => {
return response.data;
});
// <-- no return, void return
}
返回承诺
axios
当然,您需要等待 Promise 在 export default function fetchAll() {
return axios.get("/api/videos/all").then((response) => {
return response.data;
});
}
回调中解析。
useEffect