我见过State and Lifecycle in React Docs。在其中,我看到了以下句子:
但是,它错过了一个关键要求:时钟设置计时器并每秒更新UI的事实应该是时钟的实现细节。
这是什么意思?
答案 0 :(得分:0)
在文档上向下滚动时,您将看到Clock组件的完整实现是这样的:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval( //<~~ The implement of updating Timer is performed inside Clock component
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() { // <~~ The implement of updating Timer is performed inside Clock component
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')
);
请注意,现在在“时钟”组件中管理计时器。与之前在Clock组件的主体外部执行更新计时器操作时不同。
这是回弹
function Clock(props) {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
);
}
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('root')
);
}
setInterval(tick, 1000); // <~~ The increment happen outside the Clock component