【发布时间】:2019-12-07 18:24:26
【问题描述】:
我有 GUser 类,在我的项目中存储来自 GitHub-api 的数据并处理它们:
import axios from "axios";
export default class GUser {
constructor(userName) {
this.userName=userName;
this.getUserData(this,userName);
}
getUserData(that, userName) {
if(that.data===undefined)
{
axios.get('https://api.github.com/users/'.concat(userName))
.then(function (response) {
that.data = response.data;
console.log(that);
return that.data;
})
.catch(function (error) {
console.log(userName+ " got error " +error);
});
}
else{return that.data;}
}
}
我正在尝试同步页面,所以我在TestRender 中写道:
import React from 'react';
import GUser from "../model/GUser";
class TestRender extends React.Component{
userName='maifeeulasad';
user=new GUser(this.userName);
componentWillMount() {
try {
console.log(this.user.getUserData());
}
catch (e) {console.log(e);}
}
componentDidMount() {
try {
console.log(this.user.getUserData());
}
catch (e) {console.log(e);}
}
render() {
return(
<div>
</div>
);
}
}
export default TestRender;
我的目标是在收到数据后立即在控制台记录数据。
我该怎么做?
以前,当我从同一个脚本加载数据时,我只使用了componentWillMount。它目前给了我TypeError: Cannot read property 'data' of undefined,可能是因为我没有在GUser 中将data 指定为state,但它是通过时间创建的吧?
【问题讨论】:
标签: javascript reactjs asynchronous axios