簡體   English   中英

使用setTimeout的setState時如何重新渲染react-component?

[英]How can I re-render react-component when I setState using setTimeout?

我試圖編寫一個每隔幾秒鍾更新一次時間軸的組件,因此我使用了這樣的for循環並使用setTimeout使間隔更加明顯:

let tmp = this.state.colors;
// colors is an array
for(let i = 0 ; i < 4; i++){
    if(tmp[i]=="blue"){
        tmp[i]="green";
        setTimeout(function () {
            console.log(tmp);
            this.mapped.setState({
                colors: tmp
            });
        }.bind({mapped:this}), 2000);
    }
}

但是似乎無法立即重新渲染我的組件,我希望我的組件每兩秒鍾更新一次時間表,但是它只是重新渲染了一次。

而且我知道在eventHandler完成后,react處理所有setStates()我嘗試使用forceUpdate盡管我不勸阻它,但它不起作用。

那么重新渲染組件的最佳方法是什么?

任何幫助將不勝感激。


更新

謝謝@ andre-lee。

    for (let i = 0; i < 4; i++) {
        setTimeout(function () {
            tmp[i] = "green";
            this.setState({
                colors: tmp
            });
        }.bind(this), 2000 * (i + 1));
    }

上面的代碼有效。

我已經根據您的代碼段創建了一個草稿,如下所示: http://codepen.io/andretw/pen/JWmYGo

我的草案有兩個主要變化。

  1. 您應該使用2000 * i作為setTimeout 或者,您可以使用setInterval並稍后將其清除。
  2. 在setTimeout 的回調函數中更改顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM