javascript - axios 请求在 useEffect 中返回 undefined
问题描述
当我尝试在 useEffect 钩子中发出 axios 请求时,它返回 undefined,
但是在 Inspect Mode 下的 Network request 中查看时发现它是成功的
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;
});
}
};
应用程序.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
调用它的函数。
推荐阅读
- c - 如何将 CSV 文件的内容存储在链接列表中?
- java - 如何在通过 gradle for Android 项目生成 JavaDocs 时忽略/排除嵌套类
- php - 如何在 CodeIgniter 中配置 Paypal
- sql-server - SSIS 包应因参数值无效而失败
- javascript - 我无法使用 GeoSearch 在传单地图中正确搜索位置
- python - 如何从Python中的元组列表中提取第一个元素
- arrays - 如何在波形中查看 SystemVerilog 动态数组
- huawei-mobile-services - Codelab基于Health Kit开发的应用程序读取活动数据并报错怎么办?
- flutter - 如何在类中定位 Text/TextSpan
- html - 使用 role = "listbox" 输入元素是否有效?