当我尝试在useEffect钩子中进行axios请求时,它返回未定义,
但我发现在检查模式下查看网络请求时它是成功的
api.js
import axios from "axios";
export default axios.create({
baseURL: `https://jsonplaceholder.typicode.com`
});
PostService.js
import instance from "./api";
export default {
getPost: () => {
instance({
method: "GET",
url: "/posts"
})
.then((res) => {
return res;
})
.catch((err) => {
return err;
});
}
};
App.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
您的PostService
中缺少一个return
:
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
函数调用它。