Help us understand the problem. What is going on with this article?

setStateを複数回実行してもrenderは1回しか呼ばれない

More than 5 years have passed since last update.

ReactjsのsetStateとrenderの挙動をちょっと確認してみました。
具体的には以下のコードで検証。

はじめはsetStateの度にrenderが呼び出されるのかと思ってましたが
そうではなくて、stateの変更をキューに入れてrenderを呼び出す前にまとめて解決するようです。
setTimeoutでコールバックを呼んだ時なんかは
別のキューになるようです
setStateが呼ばれなければもちろんrenderも呼ばれない

app.js
var MyComponent = React.createClass({
    getInitialState: function () {
    return {
        value: 'step 0'
    };
    },
    handleClick: function() {
        this.setState({
            value: 'step 1'
        });
        console.log('called step 1');

        this.setState({
            value: 'step 2'
        });
        console.log('called step 2');

        this._func();
        this.setState({
            value: 'step 4'
        });
        console.log('called step 4');
        setTimeout(this._callback, 1000, this);
    },
    _func: function() {
        this.setState({
            value: 'step 3 this is inner func'
        });
        console.log('step 3 _func called');
    },
    _callback: function(self) {
        self.setState({
            value: 'step 5'
        });
        console.log('step 5 called');
    },
    doNothing: function() {
        console.log('do nothing');
    },
    render: function() {
        console.log('will render!');
        return (
            <div>
                <div>{this.state.value}</div>
                <a onClick={ this.handleClick }>Click me!</a>
                <p onClick={ this.doNothing }>Click me but I will do nothing</p>
            </div>
        );
    }
});
React.render(
    <MyComponent />,
    document.getElementById('app')
);

//will render! 最初
//app.js:44 called step 1
//app.js:49 called step 2
//app.js:62 step 3 _func called
//app.js:55 called step 4
//app.js:74 will render! 一回だけ呼ばれる
// 1秒空くよ
//app.js:74 will render!  順番が違う?
//app.js:68 step 5 called
ichi944
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした