javascript - 在 MERN 应用程序(React 客户端)中外包 API 调用的正确方法?
问题描述
我正在尝试在 React/MERN 应用程序中外包一些 axios API 调用。我需要在客户端启动时(在 useEffect() 中)向服务器发出 GET 请求。我已将我的 axios 函数移动到 React 客户端文件夹中的外部文件并将其导出。使用 console.log 进行测试时,该函数本身似乎可以工作,因为它获得了正确的数据。但是,当我尝试在客户端的 useEffect() 挂钩中使用该函数的返回值时,我得到未定义或 Promise(不能是 React 子级)。
这是我当前的代码:
应用程序.js
const [response, setResponse] = useState('Loading...');
useEffect(() => {
setResponse(helloMessage());
}, [])
调用API.js
const helloMessage = () => {
axios.get('http://localhost:5000/')
.then(res => {
return res.data.message;
})
.catch(() => {
return 'Server not responding. Start the server and refresh this page.';
})
}
出口和进口等都正确到位。在这种情况下,我唯一的问题可能是 async/await 的语法或其他问题(我很确定这是这里的问题)。使用外部文件中的函数进行 API 调用以设置 useEffect() 状态的正确方法是什么?
解决方案
您应该拨打电话,并在回调中更改状态。
const [response, setResponse] = useState('Loading...');
useEffect(() => {
helloMessage().then(res =>
setResponse(res);
)
}, [])
并且需要从helloMessage
const helloMessage = () => {
return axios.get('http://localhost:5000/')
.then(res => {
return res.data.message;
})
.catch(() => {
return 'Server not responding. Start the server and refresh this page.';
})
}
推荐阅读
- javascript - Wordpress - Yoast 插件框未显示在管理页面上
- mysql - 从用户端将播放列表设为公开或私有
- r - 如何生成 50 个自由度为 50 的 10 chi^2(即 \chi 平方)分布变量的观测值?
- python - Python urllib2.Request 标题响应对于 instagram 不可读
- ios - 如何在推送的视图控制器中的导航栏下方添加一行?
- python - 正则表达式仅搜索一位数字
- c - 如何更改全局数组的元素以供所有线程查看
- vim - 如何编写 vim 函数来搜索多个字符串(当我调用函数时)并突出显示所有字符串(以便我使用 n/N 移动)
- javascript - 如何使用下拉选择操作道具值
- matlab - 通过 Matlab 找到线性方程组的完整和符号解