【发布时间】:2017-05-23 00:55:48
【问题描述】:
我一直在尝试学习 react 和 next。
使用codepen 上给出的时钟示例,可在反应文档here 中找到。
我尝试在本地站点上实现它。
Clock.js - 在 /components 中
export default 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>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
index.js - 在 /pages 中
import Clock from '../components/Clock'
export default () => (
<div>
<Header />
<div id="contentWrap">
<div><Clock /></div>
</div>
</div>
)
运行 npm run dev 然后转到 localhost:3000,它会初始加载,但不会像在 codepen 上那样每秒更新一次。
我是否遗漏了一些允许更新的地方?
【问题讨论】:
-
是否有任何 JavaScript 错误? 404?您的问题类似于服务器端渲染正常但客户端挂载未发生时您将看到的那种情况。
-
代码似乎是正确的。它有效 - 控制台上是否有任何错误消息?间隔是否处于活动状态 - 您可以在 tick 函数中添加 console.log() 调用吗?
标签: javascript node.js reactjs next.js