reactjs 检查数据更新



我的项目中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中指定datastate,但它是通过时间创建的,对吗?

看起来你正在使用对象的属性来存储状态的组件,这并不好,因为当这些值更新时,React 不会重新渲染组件.
每个TestRender实例都应该具有与属性相同的userNameuser值?这些值总是相同的?如果没有,请使用useState

此外,只有在挂载组件时才会调用componentDidMountcomponentWillMount,此时您尚未完成提取,因此您还没有要打印的值。这是一个异步问题。

为了处理异步挑战,我建议使用useEffect.

最新更新