Instance v state variables in react.js

In react.js, is it better to store a timeout reference as an instance variable (this.timeout) or a state variable (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);
}
...
})

or

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);
}
...
})

both of these approaches work. I just want to know the reasons for using one over the other.

57110 次浏览

我建议将它存储在实例上,而不是它的 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);
},
...
});