【问题标题】:Where is timerID coming from? [closed]timerID 来自哪里? [关闭]
【发布时间】:2022-01-13 19:53:02
【问题描述】:

我已经理解了this.timerId 如何不会导致反应文档中的错误。

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {    this.setState({      date: new Date()    });  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

我知道 timerIdsetInterval 来自 Node。我认为节点只是运行时,除了节点计时器之外,它是否带有其他模块? timerID 是从哪里初始化和继承的?在 Node 上运行时,所有对象都获得timerID 吗?

【问题讨论】:

  • “来自节点” - 我不这么认为。由于代码看起来在浏览器中运行。 developer.mozilla.org/en-US/docs/Web/API/setTimeout
  • “timerID 是从哪里初始化和继承的?” -,this.timeId = something 是一个作业。这对于大多数编程语言的工作方式非常重要,并且在您共享的代码中。
  • 在 Node 上运行时,是否所有对象 [不,不是所有对象] 都获得 timerID [没有任何东西“获得” timerID 本身] [这与节点无关,无论是代码还是一般情况]
  • 感谢昆汀的回复,我来自java。在创建对象后能够在对象上设置新状态对我来说是陌生的。我在构造函数中看不到 timeId 。我可能因为javascript语法而感到困惑吗? this在构造过程中没有初始化timeId怎么设置?

标签: javascript node.js reactjs


【解决方案1】:

在这种情况下,this.timerID 在被分配一个值时被创建为一个新属性,正如 cmets 中的 @luk2302 所指出的那样。

下面显示了另一种可能的方式,您可以引用不是直接在该类中创建的属性,而是在父类中创建的。

class SuperClass {
    constructor() {
        this.superProperty = "Hello I'm super!"
    }
}

class SupportClass extends SuperClass{
    constructor(example) {
        super();
        this.example = example;
    }

    supportMethod() {
        console.log(this.example);
        console.log(this.superProperty);
    }

}

let supportClass = new SupportClass("HELLO");

supportClass.supportMethod();

这会产生一个输出:

HELLO
Hello I'm super!

【讨论】:

  • 谢谢克雷格。这就是我一直在寻找的。​​span>
  • 不,timerID 不是来自React.Component。你能指出一个文档来支持这个说法吗?您可以随时随地在构造函数之外创建新属性。这个答案是错误的@bdehmer,请参见例如class P{constructor(){this.a=2;}something(){this.b=1;}}p=new P();p.something();p.b
  • 这似乎是你的权利,我做了一个错误的假设。我会更改我的答案以反映您的 cmets。
猜你喜欢
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
  • 2010-09-21
  • 2014-04-24
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多