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

JavaScript

神奇神奇Near

2020-03-12

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

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

第876篇《react.js中的实例v状态变量》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
小胖Sam 2020.03.12

除了@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); 
     },
    ...
});
村村老丝 2020.03.12

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

由于的值对timeout组件的呈现没有影响,因此不应存在于中state将其放在那里会导致对的不必要调用render

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android