React初识整理(二)--生命周期的方法

React生命周期主要有7中:

1. componentWillMount() :组件将要挂载时触发 ,只调用1次

2. componentDidMount() :组件挂载完成时触发,只调用1次

3. componentWillReceiveProps(newProps) :只有props改变时触发(state改变不会触发),可以在方法中改变state。其中传入参数newProps为新的props值

4. shouldComponentUpdate(newState,newProps) :只要props或者state改变就会触发,它有1个返回布尔值,返回false后、后面的更新就不会执行了,返回ture则要执行。这样就可以用该方法阻止最后界面的渲染,可做性能优化。(不能在方法中改变state)

5. componentWillUpdate() :即将更新的时候触发,props和state改变都会触发,不能再方法中改变state

6. componentDidUpdate() :更新完成时触发,props和state改变都会触发,不能再方法中改变state

7. componentWillUnmount() :组件销毁时触发

所有时间出发先后顺序如下图示:

  注意:在render /shouldComponentUpdate /componentWillUpdate / componentDidUpdate这4个方法中不能调用改变state的方法、也不能改变state,否则会造成死循环调用,即state状态改变,然后自动又触发了状态改变的方法。

原文地址:https://www.cnblogs.com/zhangzhiyong/p/10090768.html