什么场景 react 生命周期钩子是必须的

以下是react生命周期钩子的官方案例,下面这个案例,如果我稍作改动,把setInterval 改成 setTimeout放在render() 里面,这样setTimeout 会setState, 然后循环call render(), 循环setTimeout. 也可以实现,那么这种情况用生命周期钩子为什么是必须的,或者有什么好处呢? 为了代码整洁? 为了减少memory消耗??

原官方案例


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>
    );
  }
}

```

你不能这么玩。setTimeout也有域
setTimeout(()=>{this.todo},1000)

你这个代码跑过吗 会报错吧

setState => render => setState => render一直循环下去 什么时候return呢

img


你在这个循环里出不来了呀

ref: React生命周期执行顺序详解 - xiaobe - 博客园 文章内容转载于https://www.cnblogs.com/faith3/p/9216165.html 一、组件生命周期的执行次数是什么样子的??? 二、组件的生命周期执行顺序是什么样子的??? 假 https://www.cnblogs.com/soyxiaobi/p/9559117.html

内存会泄漏,每次setState 会触发组件重新渲染,render-setState-render-setState..........自己给自己玩死了