我有一个React组件,它调用函数getAllPeople:

componentDidMount() {
   getAllPeople().then(response => {
      this.setState(() => ({ people: response.data }));
    });
  } 

getAllPeople在我的api模块中:

export function getAllPeople() {
  return axios
    .get("/api/getAllPeople")
    .then(response => {
      return response.data;
    })
    .catch(error => {
      return error;
    });
}

我认为这是一个非常基本的问题,但假设我想处理根组件(在我的componentDidMount方法中)中的错误,而不是api函数中的错误,那么这个根组件如何知道axios调用是否返回错误?例如,处理来自promise 的错误的最佳方式是什么?

推荐答案

getAllPeople函数已经返回axios调用的数据或错误消息.因此,在componentDidMount中,您需要判断调用getAllPeople的返回值,以确定返回的是错误还是有效数据.

componentDidMount() {
   getAllPeople().then(response => {
      if(response!=error) //error is the error object you can get from the axios call
         this.setState(() => ({ people: response}));
      else { // your error handling goes here
       }
    });
  } 

如果希望从api返回promise ,则不应在api中解析axios调用返回的promise .相反,您可以执行以下操作:

export function getAllPeople() {
  return axios.get("/api/getAllPeople");
}

然后你可以在componentDidMount分钟内解决.

componentDidMount() {
   getAllPeople()
   .then(response => {          
         this.setState(() => ({ people: response.data}));
     })
   .catch(error => { 
         // your error handling goes here
     }
  } 

Reactjs相关问答推荐

React,React Router,Joy UI:如何在导航离开和返回后禁用snackbar重新出现?

Redux Store未触发React组件中的重新呈现

如何从react 18-nextjs 14应用程序路由中的客户端组件呈现服务器组件?

如何在物料界面react 的多选菜单中设置最大 Select 数限制

React redux 工具包 useGetFilterProductsQuery 和 useGetFilterProductsByCategoriesQuery 未定义为函数

如何更新redux状态存在的输入框

使用reactrouterdom时显示"对象无效作为React子组件"错误

运行 npm run build 出现问题

使用 toast 时挂钩调用无效

React + Redux:数据未正确传递给具有动态路由的组件

将复杂状态和 setState 传递给更简单的 api

在 Spring Cloud Gateway 中运行的 React SPA 页面刷新出现白标错误

React Native map 中的初始zoom 级别

ReactJS:useMemo 钩子修复了我的无限重新渲染问题而不是 useEffect

如何解决在 react.js 中找不到模块错误

如何根据数据库中的值设置单选按钮选中? - react

列表应该有一个唯一的关键props

如何将本地视频文件上传到 Google Cloud

调用函数以获取数据并在数据到达时导航到链接

添加禁用的默认选项以 Select