返回语句给出未定义

时间:2021-04-03 07:41:36

标签: javascript reactjs return

我有一个函数: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 而不是数据。
非常感谢任何帮助!

1 个答案:

答案 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