McGrady
McGrady

Reputation: 11477

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

I tried to write a component that update timeline every few seconds, so I use a for loop like this and use setTimeout to make the interval more obvious:

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);
    }
}

But it seems that it can't re-render my component at once,I want my component update the timeline every two seconds, but it just re-render one time.

And I know that react process all the setStates() after the eventHandler has completed.I tried to use forceUpdate although I know it's not discouraged, but it doesn't work.

So what's the best way to re-render my component?

Any help would be great appreciated.


Update

Thanks @andre-lee.

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

The above code works.

Upvotes: 1

Views: 2572

Answers (1)

Andre Lee
Andre Lee

Reputation: 1320

I've created a draft based on your code snippet as following, http://codepen.io/andretw/pen/JWmYGo

There are two major changes in my draft.

  1. You should use 2000 * i for your setTimeout. Or you can use setInterval and clear it later.
  2. Change the color in the callback function in your setTimeout.

Upvotes: 2

Related Questions