react.js中的实例v状态变量

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)

这两种方法都有效.我只是想知道使用其中一个的原因.

Ros*_*len 158

我建议将它存储在实例上,而不是存储在实例中state.每当state更新(只应setState按照注释中的建议完成)时,React会调用render并对真实DOM进行任何必要的更改.

因为值对timeout组件的呈现没有影响,所以它不应该存在state.把它放在那里会导致不必要的电话render.


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)