首页 > 解决方案 > 在什么场景下,react生命周期钩子是必须的

问题描述

以下是 react 生命周期 hook 的官方案例。下面这种情况,如果我稍作改动,把setInterval改成setTimeout,放到render()中,这样setTimeout就会setState,然后循环调用render(),循环setTimeout。也可以实现,那么为什么在这种情况下需要使用生命周期钩子,或者有什么好处呢?清理代码?为了减少内存消耗??

官方示例:

 
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
  componentDidMount() {
    this.timerID = setInterval(
  this.setState({
      date: new Date()
    }), 1000);
  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

我的修改

 
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
 
  render() {
    this.timerID = setTimeout(
    this.setState({
      date: new Date()
    }),1000);
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

标签: reactjs

解决方案


如果您在函数中创建一个函数(在本例中为间隔)render(),这将在每个组件渲染中创建,因此在性能方面真的很糟糕,(render方法将在不到 1 秒内发生)。

componentDidMount有利于订阅或在组件挂载后做一些事情,也componentWillUnmount有利于取消订阅。

因此,当您使用间隔时,您希望将其初始化componentDidMount并清除componentWillUnmount

componentDidMount() {
    this.timer = setInterval(this.tick, 1000);
}

componentWillUnmount() {
    clearInterval(this.timer);
}

推荐阅读