react.js中的实例v状态变量 [英] Instance v state variables in react.js

查看:133
本文介绍了react.js中的实例v状态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In react.js, is it better to store a timeout reference as an instance variable (this.timeout) or a state variable (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); 
     }
    ...
})

这两个接近工作。我只是想知道使用其中一个的原因。

both of these approaches work. I just want to know the reasons for using one over the other.

推荐答案

我建议将它存储在实例上而不是存储在实例中状态。每当更新时(只应通过 setState ,如评论中所建议的),React调用 render 并进行必要的更改真正的DOM。

I suggest storing it on the instance but not in its state. Whenever state is updated (which should only be done by setState as suggested in a comment), React calls render and makes any necessary changes to the real DOM.

因为 timeout 的值对组件的渲染没有影响,所以它不应该' t住在。把它放在那里会导致不必要的调用 render

Because the value of timeout has no effect on the rendering of your component, it shouldn't live in state. Putting it there would cause unnecessary calls to render.

这篇关于react.js中的实例v状态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆