bre*_*son 111 javascript reactjs
在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);
}
...
})
Run Code Online (Sandbox Code Playgroud)
要么
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);
}
...
})
Run Code Online (Sandbox Code Playgroud)
这两种方法都有效.我只是想知道使用其中一个的原因.
Bri*_*and 11
除了@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);
},
...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
51805 次 |
| 最近记录: |