初学react之生命周期

200 阅读1分钟

一、第一个生命周期方法componentDidMount,它就是挂载,一般我们想要在进入页面时就能获取到接口请求的数据等,那么我们就可以调用componentDidMount这个生命周期函数,但是请记住这个方法只会执行一次

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
  }

  componentWillUnmount() {
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

二、当我们想要在页面渲染完毕之后去除某些操作呢,那么我们可以用到对应的生命周期函数componentWillUnmount,这个方法是指在即将卸载的时候执行你想要执行的东西,这个一般用于清除页面的一些定时器或者解绑dom等。