前端开发之React组件生命周期

来源:互联网 发布:上海老房子集中地知乎 编辑:程序博客网 时间:2024/05/22 02:09

React组件在加载时都有特定的生命周期,在此期间不同的方法会被执行。

组件有三种状态:

  • 加载:组件实例从创建到最终显示在终端
  • 更新:组件加载完成后,组件的属性(Props)或者(state)变化时,会重 新加载组件
  • 卸载:组件从有到无。从Dom元素中卸载。

每种状态下,组件调用的方法都不相同

这里写图片描述

组件加载

  • constructor()
  • componentWillMount()
  • render()
  • componentDidMount()
  • constructor()
constructor()

组件构造器,一般在构造器中,只做三件事情。
1. 继承父类属性 super(props),如果不写,this.props将没值。
2. 初期化state。如果需要把一个props值保存在组件内部时,可以在这里fork属性。
3. 绑定事件,如果组件内有触发的事件。必须在构造器中绑定。否则,事件方法内部不能获取this对象。

constructor(props) {  super(props);  this.state = {    color: props.initialColor  };  this.handleChange = this.handleChange.bind(this);}
componentWillMount()

componentWillMount会在组件render之前执行,并且永远都只执行一次。 由于这个方法始终只执行一次,所以如果在这里定义了setState方法之后,页面永远都只会在加载前更新一次。 所以,一般不会使用这个方法,用构造器取代。

render()

这里负责定义组件的“外观”,不要在这里修改组件state。也不要写任何与外观显示无关的事情。如果shouldComponentUpdate()返回false.render()不会被调用。

componentDidMount()

这个方法会在组件加载完毕之后执行。如果你想从远程获取数据,可以写在这里。更新state后,页面会刷新。

componentDidMount: function() {  setTimeout(function() {    this.setState({items: {name: 'test'}})  }, 1000)}

组件更新

  • componentWillReceiveProps()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()
componentWillReceiveProps(nextProps)

当组件的属性(props)值变化时,会调用该方法。如果新属性值需要更新state时,也可以在这里处理。当组件的属性值没有变化时,也可能会调用该方法。什么时机?当父组件刷新,自己也刷新。 这时你可以根据nextProps和this.props比较。来做特殊处理。组件在初期化时,不会调用该方法。this.setState时也不会。只有props更新时。在这里调用this.setState()方法不会增加一次新的render.

componentWillReceiveProps(nextProps) {  this.setState({    this.setState({items: {name: 'test'}})  });}
shouldComponentUpdate(nextProps, nextState)

该方法的目的是判断页面该不该刷新。返回值是true或false。默认true。 默认情况下,属性或者state更新时,都会刷新页面。 如果返回false,页面不会刷新,也表示componentWillUpdate(),render()和componentDidUpdate()不会被调用。 在这里设置this.setState不会再次刷新组件。

componentWillUpdate(nextProps, nextState)

在组件接收到新的props或者state但还没有render时被执行。在初始化时不会被执行。 在这里不能调用this.setState()。应该写componentWillReceiveProps()里。

render()

和组件加载时render相同

componentDidUpdate(prevProps, prevState)

在组件完成更新后立即执行。在初始化时不会被执行。 在这里可以操作DOM或者网络请求。

组件卸载

  • componentWillUnmount()

组件卸载和销毁时,会调用该方法,可以在这里做一些清理工作。

0 0