React生命周期

React 的生命周期:官方API

下面这个方法是组件第一次加载时执行

  1. constructor() :最先调用用
  2. componentWillMount() :render 前立即执行
  3. render() : 插入到DOM
  4. componentDidMount() : render()后立马运行,且只会运行一次

state 或props更新时,会触发render()重新执行,而以下这些方法在render()再次执行前执行:

  1. componentWillReceiveProps(nextProps) : 在接收到新的props时,this.props并未被更新,nextProps 就是新的props
  2. shouldComponentUpdate() :默认是每次state改变时,都会重新render(). 但是它在第一次render不会运行,在forceUpdate()时不会运行。return false时,render()不会执行
  3. componentWillUpdate() : 组件更新(render()确定要执行了)前的一步,这儿不能更改state。 你能想到:shouldComponentUpdate() returnfalse时,它不会运行
  4. render() : 更新DOM
  5. componentDidUpdate(),gengxinDOM后立即执行

组件完结,开始销毁:

  • componentWillUnmount() : 组件被销毁前,一般用来去掉事件监听,或者一些全局绑定,就是那些JS垃圾回收机制不会自动回收的东西

React的其他API:

  • setState() : 修改state
  • forceUpdate():这个不会导致shouldComponentUpdate() 运行,但是子组件的shouldComponentUpdate() 会执行,这个东西要少用。
  • defaultProps : 给props设置默认值。
  • propTypes:给props内的参数设置类型限制,或者必填规则(就是一定要有这个参数)

你可能感兴趣的:(React生命周期)