首页 > 解决方案 > 在 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() 状态的正确方法是什么?

标签: javascriptreactjsapiaxios

解决方案


您应该拨打电话,并在回调中更改状态。

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.';
        })
    }

推荐阅读