【发布时间】: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')
);
我知道 timerId 和 setInterval 来自 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