在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);
}
...
})
这两种方法都有效。我只想知道使用其中一个的原因。
发布于 2014-08-09 01:17:18
我建议将其存储在实例上,而不是存储在其state
中。无论何时更新state
(应该只由setState
按照注释中的建议完成),React都会调用render
并对实际的DOM进行任何必要的更改。
因为timeout
的值对组件的呈现没有影响,所以它不应该存在于state
中。把它放在那里会导致对render
的不必要的调用。
发布于 2014-08-09 04:50:47
除了@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);
},
...
});
https://stackoverflow.com/questions/25207703
复制相似问题