[英]Instance v state variables in react.js
在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);
}
...
})
這兩種方法都有效。 我只是想知道使用其中一個的原因。
我建議將它存儲在實例上,而不是存儲在其state
。 每當更新state
(應該只通過注釋中建議的setState
來完成),React調用render
並對真實DOM進行任何必要的更改。
因為timeout
值對組件的呈現沒有影響,所以它不應該處於state
。 把它放在那里會導致不必要的render
調用。
除了@ssorallen所說的,你還應該記得在調用handleLeave之前處理組件的卸載。
React.createClass({
handleEnter: function () {
// Open a new one after a delay
this._timeout = setTimeout(function () {
this.openWidget();
}.bind(this), DELAY);
},
handleLeave: function () {
// Clear the timeout for opening the widget
clearTimeout(this._timeout);
},
componentWillUnmount: function(){
// Clear the timeout when the component unmounts
clearTimeout(this._timeout);
},
...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.