首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >react.js中的实例v状态变量

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

Stack Overflow用户
提问于 2014-08-09 00:09:36
回答 2查看 56.8K关注 0票数 126

在react.js中,将超时引用存储为实例变量(this.timeout)还是状态变量(this.state.timeout)更好?

代码语言:javascript
复制
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); 
     }
    ...
})

代码语言:javascript
复制
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); 
     }
    ...
})

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-09 01:17:18

我建议将其存储在实例上,而不是存储在其state中。无论何时更新state (应该只由setState按照注释中的建议完成),React都会调用render并对实际的DOM进行任何必要的更改。

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

票数 176
EN

Stack Overflow用户

发布于 2014-08-09 04:50:47

除了@ssorallen所说的,你还应该记得在调用你的handleLeave之前处理组件卸载。

代码语言:javascript
复制
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); 
     },
    ...
});
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25207703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档