React生命周期大概有三个阶段,能够分为挂载、渲染和卸载。当渲染后的组件须要更新时,咱们会从新渲染组件,直至卸载。所以生命周期又能够分为两类:bash
下面按照分类的方式阐述生命周期(为了简洁代码只展现重要部分)dom
组件的挂载主要是初始化组件的状态,把组件的dom插入到页面中。生命周期函数执行顺序: componentWillMount --> render --> componentDidMount;
若是组件不被卸载 componentWillMount 和 componentWillMount 之会执行一次;函数
...
class App extends Component {
// 组件将要挂载到页面
componentWillMount() {
console.log(document.getElementById('con')); // null
}
// 组件已经挂载到页面
componentDidMount() {
console.log(document.getElementById('con')); // <div id="con">...</div>
}
render() {
return (
<div id="con">组件的挂载</div>
);
}
}
...
复制代码
组件的卸载能够这么理解:该组件中全部的dom都从页面中删除(注意是删除不是隐藏);
一般在componentWillUnmount中咱们经常会执行一些清理方法,好比定时器或者是时间回收ui
...
class App extends Component {
// 组件将要卸载
componentWillUnmount() {
}
render() {
return (
<div id="con">组件的卸载</div>
);
}
}
...
复制代码
组件的数据更新过程的生命周期函数有:componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、componentWillUpdate、componentDidUpdate;
执行顺序:
1.若是父组件向下传递props时执行顺序为:
componentWillReceiveProps --> shouldComponentUpdate --> componentWillUpdate --> render --> componentDidUpdate
2.若是只是组件的自身state更新了执行顺序为: shouldComponentUpdate --> componentWillUpdate --> render --> componentDidUpdate
spa
...
class Con extends Component {
// nextProps 为父组件传递的新props
// nextState 为子组件新的state
// 只在父组件传递的props更新时执行
componentWillReceiveProps(nextProps) {
}
// return 布尔值判断是否要从新渲染该组件
shouldComponentUpdate(nextProps, nextState) {
}
// 组件更新前时执行
componentWillUpdate(nextProps, nextState) {
}
// prevProps prevState 分别为更新前的props和state
// 组件更新完成时执行
componentDidUpdate(prevProps, prevState) {
}
render() {
return (
<div id="con">组件的更新</div>
);
}
}
...
复制代码
shouldComponentUpdate是一个特别的方法,它接受新的props和state,让开发者增长必要的条件判断,让其在须要的时候更新,不须要的时候不更新。所以,当该方法返回false时,组件再也不向下执行生命周期的方法。 3d