首页 > 解决方案 > 这是什么意思?

问题描述

在 React Docs 中看到过 State 和 Lifecycle。其中,我看到了以下句子:

但是,它忽略了一个关键要求:Clock 设置一个计时器并每秒更新 UI 应该是 Clock 的一个实现细节。

这是什么意思?

标签: javascriptreactjs

解决方案


在文档中向下滚动时,您会看到 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

推荐阅读