reactjs - React State 变量没有更新
问题描述
我有一个子组件列表,它将获取状态变量 this.state.loading 作为道具,它将用于从服务器中提取数据。除了这个状态变量,我还有两个状态变量来控制按钮属性是否刷新。我的问题是单击按钮时组件中的状态变量没有更新。我看到正在调用 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;
解决方案
变量工作正常。你只是不知道异步任务是如何工作的。看,您在函数开始时设置了初始状态。在一些 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:'',
};
});
};
推荐阅读
- mysql - 在存储过程中在mysql中编写准备好的语句
- reactjs - 我们可以在 react redux 中有多个商店吗
- azure - cosmosdb 设置 Azure 中的主机在哪里?
- clojure - Lighttable 无法连接 - 运行 Clojure REPL 时出错
- php - 如何查看特定课程的主题
- python - Tensorflow 没有为任何变量 tf.to_double 提供梯度
- javascript - 我喜欢在线合并链表解决方案,但我不太了解while循环
- php - 从 JSON 中检索数据
- c# - Unity 中安卓设备上的战争迷雾
- jquery - 如何在除 div 之外的任何地方单击时关闭 div?