作为React的初学者,我正在尝试在异步函数调用后更新我的组件状态。我有三个文件:Dashboard.js和GetInfos。
GetInfos在这里执行我的获取,Dashboard正在处理我的数据并将其发送到ComponentC,ComponentC在这里显示信息。我的第一个问题是,我不明白如何使用异步值修改我的状态,该值可以从getValue函数中记录。我不确定我是否有权;架构";在我的项目中,完全不确定这是否是正确的做事方式。
欢迎任何帮助/建议。下面,我的实际代码
GetInfos有一个返回获取值的函数:
export async function RetrieveInfos(){
const dataJobs = await retrieveDataJobs(url,id)
return dataJobs;
}
我的Dashboard的简化版本是:
class Dashboard extends React.Component{
constructor(props){
super(props);
this.state = {
dataJobs: 0
}
}
componentDidMount(){
let myDataJobs;
async function getValue(){
myDataJobs = await RetrieveInfos();
//here I can log my async value
return myDataJobs
}
// here I can use this.setState to modify my State, but not with my async value..
}
render(){
return
<Col>
<ComponentC label="Data Jobs"
value={this.state.dataJobs}
/>
</Col>
}
解决方案是异步函数GetValue没有;this.setState";上下文正确。
我更改组件DidMount,我的功能将自动执行:
componentDidMount(){
(async () => {
let myDataJobs
myDataJobs = await RetrieveInfo();
this.setState({dataJobs:myDataJobs})
})();
};
谢谢你的帮助!