Reactjs 无法在同一函数中两次更新状态变量以显示/隐藏加载程序
我试图在单击按钮时显示加载程序,并在数据加载后隐藏该加载程序。但不知何故,我无法做到这一点。很确定这是一个愚蠢的错误,但不幸的是我无法定位。请在下面找到代码的一部分Reactjs 无法在同一函数中两次更新状态变量以显示/隐藏加载程序,reactjs,Reactjs,我试图在单击按钮时显示加载程序,并在数据加载后隐藏该加载程序。但不知何故,我无法做到这一点。很确定这是一个愚蠢的错误,但不幸的是我无法定位。请在下面找到代码的一部分 /* button click function, this function will be carried to a child component, which will invoke once the button in child component is clicked */ constructor(
/* button click function, this function will be carried to a child component, which will invoke once the button in child component is clicked */
constructor(props) {
super(props);
this.state = {
loadingPoints: false
}
}
searchWithChosenFilter = (data) => {
this.setState(state => { // THIS IS NOT WORKING
return {
...this.state,
loadingPoints: true
}
})
Service.someService()
.then(response => {
this.setState(state => { // THIS IS WORKING
return {
...this.state,
loadingPoints: false
}
});
})
.catch(error => {
this.setState({
...this.state,
loadingPoints: false
});
})
}
我之所以这么说是因为在我的代码中,我放置了一个控制台,它在setstate函数调用之后打印
this.state
。请放心,这个.state
是有效的,因为我使用的是一个箭头函数,所以不要为此而挖苦。只是我不知道如何准确地进行两次setstate调用。是因为事件是在子组件中发生的,是因为。。。另外,函数中也遵循prevState
或preAnything
规则,但我使用的是类。此外,这不是垃圾话的地方。这是一个让开发人员加入他们的想法来构建更好的解决方案的地方,而不是指责和贬低他们。小心点,这很公平。阅读setState
将澄清所有问题。祝你好运。