当我尝试在 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] 删除。
我来说两句