【问题标题】:How to fetch data asynchronously in componentDidMount by AxiosAxios如何在componentDidMount中异步获取数据
【发布时间】:2020-02-29 23:56:19
【问题描述】:

我正在尝试这种方式:-

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。当我获取这些数据时,我必须渲染这些数据。

【问题讨论】:

    标签: reactjs async-await axios


    【解决方案1】:

    这是一个简单的 JS 中的 async-await 用例:

    async function asyncFunc() {
          const data = await axios.get("/url_endpoint")
                             .then((response) => return response.data)
    
          return data;
    }
    

    Async 函数返回一个 Promise 并且 Await 只能在 async 块内使用。 您可以在类组件的 ComponentDidMount() 方法中调用此函数。 我认为您可以从 componentDidMount 中删除 async 并在其中等待。

    【讨论】:

      【解决方案2】:

      不要使用awaitthen

      export default class CurdApi {
      
      static async getAllProfiles() {
      
          return await axios({
           url: 'http://localhost:8080/all/profile',
           method: 'GET',
           responseType: 'json',
         })
      
        }
      }
      

      【讨论】:

        【解决方案3】:

        getAllProfiles 没有返回语句,因此它没有返回任何内容。 .then 回调确实有 return 语句,但那些只是从它们的内部函数返回,而不是外部函数。我建议采用 async/await 并将其更改为:

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

        【讨论】:

          猜你喜欢
          • 2019-05-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-25
          • 1970-01-01
          • 2021-11-20
          • 1970-01-01
          • 2022-01-13
          • 1970-01-01
          相关资源
          最近更新 更多