我是新来的人。我想编写一个组件,该组件在按下按钮时显示5秒钟的加载动画,而其他时候则显示一个简单的“ hello world”。这是我的代码:
@foreach ($data->computers as $productcomputers)
@foreach ($data->cameras as $productcameras)
@foreach ($data->mobiles as $productmobiles)
但是,按下按钮并更改import React, { Component } from 'react';
import ReactLoading from 'react-loading';
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
class Test extends Component {
constructor(props) {
super(props);
this.state = {
data: [], // will hold the results from our ajax call
loading: false, // will be true when ajax request is running
}
}
test1() {
setTimeout(function() {
this.setState({ loading: true }, () => {
sleep(5000);
this.setState({loading: false});
});
}.bind(this), 0);
}
onClick = () => {
this.test1();
}
render() {
const { data, loading } = this.state;
return (
<div>
<button onClick={this.onClick}>
Load Data
</button>
{loading ? <ReactLoading className={'my-icon'} type={"spin"} color={"black"} height={'50%'} width={'100%'} delay={100}/> : 'HelloWorld'}
</div>
);
}
}
export default Test;
的状态后,组件不会更新。它只会在那5秒钟的睡眠后更新,所以我再也看不到加载图标。
有什么办法解决此问题吗?
谢谢。
答案 0 :(得分:2)
您可以执行此操作,无需外部睡眠功能,
test1() {
this.setState({ loading: true }, () => setTimout(()=>{this.setState({loading: false})},5000))
}