javascript - 这是什么意思?
问题描述
我在 React Docs 中看到过 State 和 Lifecycle。其中,我看到了以下句子:
但是,它忽略了一个关键要求:Clock 设置一个计时器并每秒更新 UI 应该是 Clock 的一个实现细节。
这是什么意思?
解决方案
在文档中向下滚动时,您会看到 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
推荐阅读
- c# - 如何允许用户从列表框中复制项目并粘贴到 Windows 窗体之外
- reactjs - 使用 jest 进行多环境测试
- async-await - 从任务列表中捕获异常
- java - If Else - Else 在 Java Netbeans 中无法正常工作
- sql - 如何在 SQL Server 中选择最近 7 天的日期
- javascript - 如何使用 Javascript 访问另一个带有空括号(内部没有点)的对象中的对象?
- google-app-maker - Google App Maker - SuggestBox - 小部件的数据源未处于“加载”状态
- spring - 在响应标头中检索令牌时出现问题 - Angular 6 - 后端 Spring
- python - VisPy 中体素的透明度
- jquery - 使用 DTO 对象作为参数将数据提交到 Web API