[英]Show spinner when data is loading on react
i'm having some trouble showing the spinner "" when i'm getting some data. 当我获取一些数据时,在显示微调框“”时遇到了一些麻烦。 I have a state.isLoading but i can't seem to set that to true before the getdata.getPossible() function starts.
我有一个state.isLoading,但是在getdata.getPossible()函数启动之前,我似乎无法将其设置为true。 Heres what i have:
这是我所拥有的:
class GetData extends Component {
constructor() {
super();
this.state = {
lastdraw: {},
alldraws: [],
bets: [],
isLoading: false,
showBets: false
};
}
componentDidMount() {
getdata.getLastResult().then((result) => {
this.setState({lastdraw: result.data.drawns[0]})
})
}
getMore() {
this.setState({isLoading: !this.state.isLoading})
this.setState({bets: getdata.getPossible(5), showBets: !this.state.showBets})
}
render() {
return (
<div>
<h1>{this.props.title}</h1>
<h3>{moment(this.state.lastdraw.date).format('LL')}</h3>
<div><span>{this.state.lastdraw.numbers}</span> + <span>{this.state.lastdraw.stars}</span></div>
<Btn onClick={this.getMore.bind(this)}>Generate</Btn>
{this.state.showBets ? this.state.bets.map((bet, i) => {return (<PossibleKey key={this.state.bets[i].key} bets={bet}/>)}) : null}
<Loader show={this.state.isLoading}/>
</div>
);
}
}
And the Loader component is like this: 加载程序组件是这样的:
function Loader(props) {
return props.show ? (
<div className='overlay'>
<div className='leftEye'></div>
<div className='rightEye'></div>
<div className='mouth'></div>
<p>The Universe is aligning. Please wait...</p>
</div>
) : null
}
What i want to achieve is a way for the loader component to be used elsewhere just by setting the isLoading state true or false. 我要实现的是仅通过将isLoading状态设置为true或false即可在其他地方使用加载程序组件的方法。 The getMore() function only triggers the Loader state after it executes getPossible(n).
getMore()函数仅在执行getPossible(n)后才触发加载程序状态。
I think it may be something to do with the Loader receiving props only after state is set (or maybe not!!). 我认为这可能与装入器仅在状态设置后才接收道具有关(或可能没有!)。 How can i trigger the Loader on/off ?!
如何触发开/关装载机?
If you want to do something after state has updated - you can pass a callback to state method like this 如果您想在状态更新后做些什么-您可以将回调传递给状态方法,如下所示
getMore() {
this.setState({isLoading: !this.state.isLoading}, () => {
this.setState({bets: getdata.getPossible(5), showBets: !this.state.showBets})
})
}
This should set the state isLoading before getPossible
is called 这应该设置状态isLoading之前
getPossible
被称为
Sometimes the issue is sequencing the setState
. 有时问题是对
setState
排序。 Try this: 尝试这个:
getMore() {
this.setState({isLoading: !this.state.isLoading}, () => {
this.setState({bets: getdata.getPossible(5), showBets: !this.state.showBets})
})
}
Is this your target? 这是您的目标吗?
getMore() {
if (!this.state.isLoading) {
this.setState({isLoading: !this.state.isLoading, bets: getdata.getPossible(5), showBets: !this.state.showBets})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.