首页 > 解决方案 > Axios如何在componentDidMount中异步获取数据

问题描述

我正在尝试这种方式:-

state = {
    profiles: [],
    data: []
}

async componentDidMount() {
    try {
     // this commented code works. But I want to use axios api.
    //   const response = await fetch(`http://localhost:8080/all/profile`);
    //   const json = await response.json();
    //   this.setState({ data: json });
    //   const json = await response.json();
        let response = await CurdApi.getAllProfiles(); // response always undefined. 

        this.setState({ data: response });
    } catch (error) {
      console.log(error);
    }
}

我的 CurdApi 课程在这里:-

export default class CurdApi {

  static async getAllProfiles() {
    await axios({
      url: 'http://localhost:8080/all/profile',
      method: 'GET',
      responseType: 'json',
    })
    .then((response) => {
      return response.data;
    })
    .catch((error) =>{
      return error.data;
    });
  }
} 

我是 ReactJs 和 JS 的新手。我不明白如何正确使用这个 async/await。当我获取这些数据时,我必须渲染这些数据。

标签: reactjsasync-awaitaxios

解决方案


不要使用awaitthen

export default class CurdApi {

static async getAllProfiles() {

    return await axios({
     url: 'http://localhost:8080/all/profile',
     method: 'GET',
     responseType: 'json',
   })

  }
}

推荐阅读