首页 文章

使用Javascript在类方法中定义内部类变量?

提问于
浏览
1

这个问题实际上与React JS有关 . 可以在其中一个类方法中定义内部类变量,然后在其他方法中使用它吗?我的意思是做这样的事情:

class Something extends React.Component {
  state = {
      value: 'doesnt matter'
  };

  something = () => {
    //a lot is happening in here and at some point I define this.thing
    this.thing = 1;
  }

  increase = () => {
    if(this.thing) {
      this.thing += 1;
    }
  }

  decrease = () => {
    if(this.thing && this.thing > 0) {
      this.thing -= 1;
    }
  }

  render() {
    return (
      <span>this.state.value</span>
    );
  }
}

事情是我不需要将 this.thing 作为状态值,因为我只需要内部 . 请注意,这段代码只是一个例子,实际代码有点复杂,但主要问题是,可以像我在我的例子中那样定义类内部变量( this.thing )吗?或者也许我应该这样做?什么是最佳做法?

2 回答

  • 0

    使用构造函数来做这样的事情并不是一个问题,但是基于反应理论和UI渲染这种用法不会重新渲染或遵循触发器的反应模式并重新渲染,它只是服务器作为存储对于与反应生命周期无关的值 .

    class Something extends React.Component {
      constructor(props) {
        super(props);
        // Your thing
        this.thing = 0;
        this.state = {
          value: "doesnt matter."
        };
      }
    
      something = () => {
        //a lot is happening in here and at some point I define this.thing
        this.thing = 1;
      };
    
      increase = () => {
        if (this.thing) {
          this.thing += 1;
        }
      };
    
      decrease = () => {
        if (this.thing && this.thing > 0) {
          this.thing -= 1;
        }
      };
    
      render() {
        this.something();
        console.log(this.thing); // will equal 1.
        return <span>{this.state.value}</span>;
      }
    }
    
  • 0

    我不需要把它作为一个状态值,因为我只需要内部 .

    React组件的 state 也应仅在内部使用 .

    什么是最佳做法?

    您可以使用实例变量(ivars)而不是状态到 increase performance ,因为您可以减轻事件队列的负担 . 在美学上,ivars通常需要 less code . 但状态更新通常是首选,因为它们会触发重新渲染;这个保证使您的代码 easier to think about ,因为渲染永远不会陈旧 . 在您的情况下,渲染函数独立于 this.thing ,因此可以将其存储在ivar中 .

    通常,最好在constructor中初始化ivars,因为它首先运行,所以 this.thing 保证可以被其他方法使用:

    constructor(props) {
      super(props);
      this.thing = 0;
    }
    

相关问题