在 MERN 应用程序(React 客户端)中外包 API 调用的正确方法?

Posted

技术标签:

【中文标题】在 MERN 应用程序(React 客户端)中外包 API 调用的正确方法?【英文标题】:Correct way to outsource API calls in a MERN app (React client)? 【发布时间】:2020-07-29 22:46:36 【问题描述】:

我正在尝试在 React/MERN 应用程序中外包一些 axios API 调用。我需要在客户端启动时(在 useEffect() 中)向服务器发出 GET 请求。我已将我的 axios 函数移动到 React 客户端文件夹中的外部文件并将其导出。使用 console.log 进行测试时,该函数本身似乎可以工作,因为它获得了正确的数据。但是,当我尝试在客户端的 useEffect() 钩子中使用该函数的返回值时,我得到 undefined 或 Promise(不能是 React 子级)。

这是我当前的代码:

App.js

const [response, setResponse] = useState('Loading...');

useEffect(() => 
  setResponse(helloMessage());
, [])

CallAPI.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() 状态的正确方法是什么?

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于在 MERN 应用程序(React 客户端)中外包 API 调用的正确方法?的主要内容,如果未能解决你的问题,请参考以下文章

MERN Stack - Express 和 React 在同一个端口上?

[react] Mern和Yeoman脚手架有什么区别?

MERN-stack使用react-router用户身份验证而不使用redux

关于 MERN 文件夹结构以及在何处定义 MongoDB 连接的建议

如何使用 GraphQL 在 MERN 应用程序的 MongoDB 模式中插入数组字段?

json.parse 触发 React / MERN 中的跨域错误