LoginSignup
12
7

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-03-29

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
12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7