react.js では、タイムアウト参照をインスタンス変数 (this.timeout) として保存する方がよいのでしょうか、それとも状態変数 (this.state.timeout) として保存する方がよいのでしょうか?
React.createClass({
handleEnter: function () {
// Open a new one after a delay
var self = this;
this.timeout = setTimeout(function () {
self.openWidget();
}, DELAY);
},
handleLeave: function () {
// Clear the timeout for opening the widget
clearTimeout(this.timeout);
}
...
})
または
React.createClass({
handleEnter: function () {
// Open a new one after a delay
var self = this;
this.state.timeout = setTimeout(function () {
self.openWidget();
}, DELAY);
},
handleLeave: function () {
// Clear the timeout for opening the widget
clearTimeout(this.state.timeout);
}
...
})
どちらのアプローチも機能します。どちらか一方を使用する理由を知りたいだけです。
ベストアンサー1
インスタンスに保存することをお勧めしますが、 には保存しないでくださいstate
。state
が更新されるたびに(これはsetState
コメントで示唆されているように、React はrender
実際の DOM を呼び出して必要な変更を加えます。
の値はtimeout
コンポーネントのレンダリングには影響しないため、 には格納しないでくださいstate
。 に格納すると、 への不要な呼び出しが発生しますrender
。