axios 请求在 useEffect 中返回 undefined

中交所

当我尝试在 useEffect 钩子中发出 axios 请求时,它返回未定义,
但我发现在检查模式下的网络请求中查看时它是成功的

api.js

import axios from "axios";

export default axios.create({
  baseURL: `https://jsonplaceholder.typicode.com`
});

邮政服务.js

import instance from "./api";

export default {
  getPost: () => {
    instance({
      method: "GET",
      url: "/posts"
    })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        return err;
      });
  }
};

应用程序.js

import "./styles.css";
import { useEffect } from "react";

import PostService from "./PostService";

export default function App() {
  useEffect(() => {
    async function fetchData() {
      const response = await PostService.getPost();
      console.log(response); //return undefined
    }
    fetchData();
  }, []);

  return (
   ...
  );
}

CodeSandBox:https ://codesandbox.io/s/happy-leftpad-cz12i ? file =/ src/App.js

我也是乔

return在你的PostService:

import instance from "./api";

export default {
  getPost: () => {
    return instance({
      method: "GET",
      url: "/posts"
    })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        return err;
      });
  }
};

没有return,PostService正在调用 api 并获取数据,但它不会将任何内容发送回fetchData调用它函数。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章