我有一个子组件Listing,它将获得状态变量this.state.loading作为prop,它将用于从服务器重新获得数据。与这个状态变量一起,我还有另外两个状态变量,它们控制是否刷新按钮属性。我的问题是单击按钮时组件中的状态变量没有得到更新。我看到正在调用REST调用,但是第二个REST调用似乎不起作用。如果我只是在浏览器上拨打电话,则第二次休息电话将起作用。请检查为什么状态变量没有得到更新,以及为什么第二个Rest api在浏览器上而不在此程序中起作用。谢谢
class App extends React.Component{
state ={
loading:false,
childload:true,
placeholder:'',
};
enterLoading = () => {
this.setState( ()=> {
return {
loading: true,
placeholder:'Refresh started',
childload:false,
};
});
fetch("api/doScrape")
.then(response => {
if (response.status > 400) {
return this.setState(() => {
return { placeholder: "Something went wrong during Scraping data" };
});
}
});
fetch("api/doCalc")
.then(response => {
if (response.status > 400) {
return this.setState((placeholder) => {
return { placeholder: "Something went wrong during Vix Calc!" };
});
}
});
this.setState(() => {
return {
loading: false,
childload:true,
placeholder:'',
};
});
};
render()
{
return (<div className="App">
<h1> Calculations</h1>
<Button type="primary" loading={this.state.loading} onClick={() => this.enterLoading()}>
Refresh
</Button>{this.state.placeholder}
<Listing loading={this.state.childload}/>
</div>);
}
}
export default App;
答案 0 :(得分:0)
变量正常工作。您只是不知道异步任务如何工作。看,您在函数的开始处设置了初始状态。在进行一些ASYNC调用之后,可以设置这些变量而不是其他值。这就是为什么您的功能无法正常工作的原因。
enterLoading = () => {
// THERE
this.setState( ()=> {
return {
loading: true,
placeholder:'Refresh started',
childload:false,
};
});
fetch("api/doScrape")
.then(response => {
if (response.status > 400) {
return this.setState(() => {
return { placeholder: "Something went wrong during Scraping data" };
});
}
});
fetch("api/doCalc")
.then(response => {
if (response.status > 400) {
return this.setState((placeholder) => {
return { placeholder: "Something went wrong during Vix Calc!" };
});
}
});
//AND THERE
this.setState(() => {
return {
loading: false,
childload:true,
placeholder:'',
};
});
};