React生命周期总结

react生命周期流程

1.初始化,首次render

  • getDefaultProps()

    getDefaultProps 方法可以用来设置组件属性的默认值,在组件被建立时候就立即调用,所有实例都可以共享这些属性。此时并不可以使用this.state和setState。
    注意es6语法中就不这样用了,在前面一篇文章中介绍过了区别。

  • getInitialState()

    getInitialState 方法用于定义初始状态,也不可以使用this.state和setState。

  • componentWillMount()

    componentWillMount只在初始化时候被调用一次,可以使用setState方法,会立即更新state,然后接着进行render。
  • render()

    注意在render中千万不可使用setState方法,不然马上会引起无限的报错了哈哈。如果其中包含其他的子组件,那么子组件的生命周期才开始进行。
  • componentDidmount()

    在子组件也都加载完毕后执行,在RN中就是指组件初始化加载完毕,在react中DOM渲染完成,此时就可以操作DOM了。

2.props发生改变时候更新

  • componentWillReceiveProps(nextProps)

    componentWillReceiveProps方法可以比较this.props和nextProps来看是否发生了变化,然后可以进行setState等操作。

    注意只要父组件此方法触发,那么子组件也会触发,也就是说父组件更新,子组件也会跟着更新。
  • shouldComponentUpdate(nextProps, nextState)

    shouldComponentUpdate 方法在接收了新的props或state后触发,你可以通过返回true或false来控制后面的生命周期流程是否触发。

  • componentWillUpdate(nextProps, nextState)

    componentWillUpdate在props或state改变或shouldComponentUpdate返回true后触发。不可在其中使用setState。
  • render()

    重新渲染。
  • componentDidupdate(prevProps, prevState)

    会等子组件也都更新完后才触发。

3.state发生改变时候更新

  • shouldComponentUpdate(nextProps, nextState)

    shouldComponentUpdate 方法在setState后state发生改变后触发,你可以通过返回true或false来控制后面的生命周期流程是否触发。

  • componentWillUpdate(nextProps, nextState)

    componentWillUpdate在state改变或shouldComponentUpdate返回true后触发。不可在其中使用setState。
  • render()

    重新渲染。
  • componentDidupdate(prevProps, prevState)

    会等子组件也都更新完后才触发。

3.组件销毁

  • componentWillUnmount()

    组件销毁时候触发。

使用redux时候情况

在使用redux做状态管理时候,基本不需要透过生命周期去做setState这样的状态管理了,基本都是用props来传递来重新渲染,需要注意的仅仅是在哪个生命周期时候触发action,比如需要进行ajax请求时候一般都是在componentDidMount和componentWillReceiveProps时候进行,在reducer中处理完,然后在通过props传入组件执行组件的更新周期。

参考资料

1.react生命周期

2.掘金

3.ajax请求

转载于https://www.cnblogs.com/lijie33402/p/6384080.html

猜你喜欢

转载自blog.csdn.net/ky1in93/article/details/81333947