【发布时间】:2020-06-04 00:16:01
【问题描述】:
我正在学习带有 Clock 类的章节 State and lifecycle in reactJS,但我不明白为什么我可以在 CodePen 中使用此代码时重新呈现不是状态的变量“myFirstNumber, mySecondNumber, myWord”:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
};
this.mySecondNumber = 0;
}
componentDidMount() {
this.myFirstNumber = 0;
this.myWord = "Start";
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date(),
});
this.myFirstNumber += 1;
this.mySecondNumber += 1;
if (this.myFirstNumber ===5) {
this.myWord = "Finish";
}
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
<h2>myFirstNumber from ComponentDidMount: {this.myFirstNumber}</h2>
<h2>mySecondNumber from constructor: {this.mySecondNumber}</h2>
<h2>myWord: {this.myWord}</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
render 方法每秒钟为我的非状态变量渲染所有 DOM?
【问题讨论】:
-
状态变量与否,它们仍然是变量。
标签: javascript reactjs class state setstate