我想制作一个 Clock 类组件,它在类的状态中包含一个日期属性。问题是,我希望它使用 setState({})
方法每秒更新一次。这就是我正在尝试的:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date().toLocaleTimeString()};
}
updateClock() {
setInterval(this.setState({date: new Date().toLocaleTimeString()}), 1000);
}
render() {
return (
<div>
<h2>It is {this.state.date}.</h2>
{this.updateClock()}
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.querySelector('.container')
);
有什么想法吗? 这是我在控制台中得到的
bundle.js:14420 Warning: Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
at invariant (bundle.js:12885)
at scheduleWorkImpl (bundle.js:27206)
at scheduleWork (bundle.js:27163)
at Object.enqueueSetState (bundle.js:21725)
at Clock.Component.setState (bundle.js:13204)
at Clock.updateClock (bundle.js:113)
at Clock.render (bundle.js:128)
at finishClassComponent (bundle.js:23470)
at updateClassComponent (bundle.js:23438)
at beginWork (bundle.js:24063)
最佳答案
不要在渲染中执行此操作,因为您将在许多间隔运行并尝试完全 setState
的情况下运行。在组件挂载时执行一次:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date().toLocaleTimeString()};
this.intervalId = null;
}
componentDidMount() {
this.updateClock();
}
componentWillUnmount() {
clearInterval(this.intervalId)
}
updateClock() {
setInterval(() => this.setState({date: new Date().toLocaleTimeString()}), 1000);
}
render() {
return (
<div>
<h2>It is {this.state.date}.</h2>
</div>
);
}
}
此外,不要忘记在组件卸载时停止间隔。
关于javascript - 在 ReactJS 中每秒更新一次时钟元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50435329/