reactjs - 方法在 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 {}
请帮忙
解决方案
这就是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);
}
}
推荐阅读
- python - 将 url 列表写入单元格,然后写入 pd.to_excel。URL 列表变成一个 url。如何避免这种情况?
- ios - iPad - 有没有办法有条件地保持本机键盘关闭?
- regex - 有没有办法使用正则表达式多次匹配花括号中的特定模式?
- javascript - 输入清除时输入值复位
- laravel - 如何使用 Laravel Query Builder 仅在一个连接表中进行区分?
- wordpress - Wordpress:您可以在 add_image_size() 上设置宽度条件吗
- python - 有没有办法通过 PyCharm 修改 docker 内的文件?
- laravel - 上传文件数组 Laravel
- sql - 使用 Excel 公式时的 PostgreSQL 转义字符
- java - 在 Java Hashmap 中捕获错误条件