Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@ichi944

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

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
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
7
Help us understand the problem. What are the problem?