【问题标题】:Return statement giving undefined返回语句给出未定义
【发布时间】:2021-06-29 21:15:13
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs return


    【解决方案1】:

    问题

    fetchAll 函数没有返回任何内容。

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

    解决方案

    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();
    },[]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2021-02-06
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多