React生命周期概述
React生命周期大概有三个阶段,可以分为挂载、渲染和卸载。当渲染后的组件需要更新时,我们会重新渲染组件,直至卸载。因此生命周期又可以分为两类:
- 当组件挂载或者卸载时;
- 当组件接受新的数据时更新时;
下面按照分类的方式阐述生命周期(为了简洁代码只展示重要部分)
1.组件挂载与卸载
1.1组件的挂载(componentWillMount, componentWillMount)
组件的挂载主要是初始化组件的状态,把组件的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>
);
}
}
...
复制代码
1.2组件的卸载(componentDidMount)
组件的卸载可以这么理解:该组件中所有的dom都从页面中删除(注意是删除不是隐藏);
通常在componentWillUnmount中我们常常会执行一些清理方法,比如定时器或者是时间回收
...
class App extends Component {
// 组件将要卸载
componentWillUnmount() {
}
render() {
return (
<div id="con">组件的卸载</div>
);
}
}
...
复制代码
2.组件的数据更新过程
组件的数据更新过程的生命周期函数有:componentWillReceiveProps、shouldComponentUpdate、componentWillUpdate、componentWillUpdate、componentDidUpdate;
执行顺序:
1.如果父组件向下传递props时执行顺序为:componentWillReceiveProps --> shouldComponentUpdate --> componentWillUpdate --> render --> componentDidUpdate
2.如果只是组件的自身state更新了执行顺序为:
shouldComponentUpdate --> componentWillUpdate --> render --> componentDidUpdate
...
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时,组件不再向下执行生命周期的方法。