首页 > 解决方案 > 方法在 Axios 返回 reactjs 中获取的数据之前提前返回

问题描述

我正在使用 axios.post 方法从服务器获取数据,但它提前返回。我使用了 async 和 await 但数据没有更新

apiService.js

export const  getAppAuthUser = async (page, authorizedType) => {

    await axios.post(APIURL.apiURL, JSON.stringify({
        page: page,
        authorized: authorizedType
    }), {
        headers: {

            'Content-Type': 'application/json'
        }
    }).then(res => {
        console.log(res);
        return res.data;
    }).catch(err => {
        console.log(err);
    });
}

组件.js

import * as Users from '../api/apiService';
class User extends Component {
    sortedInfo = {};
    componentDidMount() {
        this.data=Users.getAppAuthUser(1,true);
        console.log(this.data);
    }
} 

当我控制台它返回 Promise {}

请帮忙

标签: reactjsaxiosnext.js

解决方案


这就是async函数的作用:它们返回承诺。async/await存在是为了使使用 Promise 的语法更容易,但它不会改变涉及 Promise 的事实。要获取 Promise 中的值,您需要使用 Promise 的.then方法,或者将您的代码放在异步函数中并等待其结果。

您的 getAppAuthUser 函数中还有一个问题,即您没有返回任何内容,因此承诺将解析为未定义。当您将.then样式与async/await样式混合时,产生此类问题要容易得多。我强烈建议只选择一种风格并始终如一地使用它。

export const getAppAuthUser = async (page, authorizedType) => {
  try {
    const res = await axios.post(APIURL.apiURL, JSON.stringify({
      page: page,
      authorized: authorizedType
    }), {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    console.log(res);
    return res.data;
  } catch (err) {
    console.log(err);
  }
}

import * as Users from '../api/apiService';
class User extends Component {
    sortedInfo = {};
    async componentDidMount() {
        this.data = await Users.getAppAuthUser(1,true);
        console.log(this.data);
    }
} 

推荐阅读