javascript - 在 ReactJS 中每秒更新一次时钟元素

标签 javascript reactjs

我想制作一个 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/

相关文章:

javascript - KnockoutJS 未在复选框列表中选择选中的值

javascript - Angular 4 : Getting component property values. 我做错了什么?

javascript - 如何为所有子元素设置填充?

javascript - 如何更改 extjs 4.2.2 行编辑器中的按钮文本?

javascript - 等待弹出窗口javascript

javascript - 将参数传递给 React 中的 props 函数

javascript - ReactJS:获取JSON

reactjs - React Native - Bottom Sheet 始终显示在安装上

reactjs - 是否可以根据子组件 props 推断父组件 props

javascript - (codesandbox) 如何让所有标签 `checkbox` 和 `first option` 默认被选中