![](/img/trans.png)
[英]Connected React component unnecessarily re-renders when parent re-renders
[英]React: Component re-renders only when method is finished
我是新來的。 我想編寫一個組件,該組件在按下按鈕時顯示5秒鍾的加載動畫,而其他時候則顯示一個簡單的“ hello world”。 這是我的代碼:
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;
但是,在按下按鈕並更改狀態{loading: true}
,組件不會更新。 它只會在那5秒鍾的睡眠后更新,所以我再也看不到加載圖標。
任何想法如何解決這一問題?
提前致謝。
您可以執行此操作,無需外部睡眠功能,
test1() {
this.setState({ loading: true }, () => setTimout(()=>{this.setState({loading: false})},5000))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.