您的位置:首页 > Web前端 > React

React 生命周期

2019-10-25 11:28 1551 查看
原文链接:https://www.mk2048.com/blog/blog.php?id=h01c12hh02bb&title=React+%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F

React生命周期

如图:

 

一、装载(初始化)过程(Mount)

组件第一次在DOM树渲染的过程

1)getDefaultProps() :

ES5中设置默认的props(ES6中defaultProps设置组件的默认的属性)。

2)getInitialState() :

ES5中初始化state,此时可以访问this.props。

3)componentWillMount() :

在组件被挂载前调用,整个生命周期只执行一次。

4)render():

渲染组件,创建虚拟DOM,更新DOM树(不能更改state了),必须实现该方法。

5)componentDidMount():

在组件渲染之后调用,已经生成真实的DOM节点,只执行一次。

 

二、更新过程(Update)

组件被重新渲染的过程(初始化时均不调用)

1)componentWillReceiveProps(nextProps):

父组件的render()方法执行后就会调用。

2)shouldComponentUpdate(nextProps, nextState):

当state或者props改变时调用,有返回值true/false。

若返回true,则继续执行render();若返回false则放弃本次渲染(对于react性能优化非常重要)。

forceUpDate会越过shouldComponentUpdate(nextProps, nextState)重新渲染。

3)componentWillUpdate(nextProps, nextState):

只有在组件将要更新时才调用,此时可以修改state。

4)render():

渲染组件

5)componentDidUpdate():

组件更新完成后调用,此时可以获取dom节点。

 

三、卸载过程(Unmount)

组件从DOM树中删除的过程

1)componentWillUnmount():

组件将要卸载时调用,将组件从DOM树移出,防止内存溢出(如:事件监听、定时器)。

 

四.例子

1.HTMI

<div id="app"></div>

2.JS

class Components extends React.Component {

constructor(props){
super(props);
this.state = {}
}
componentWillMount(){
console.debug("实例化:componentWillMount")
}
componentDidMount(){
console.debug("实例化:componentDidMount")
}
componentWillReceiveProps(){
console.debug("存在期:componentWillReceiveProps")
}
shouldComponentUpdate(nextProps,nextState){
console.debug("存在期:shouldComponentUpdate",nextProps,nextState)
return true;
}
componentWillUpdate(){
console.debug("存在期:componentWillUpdate")
}
componentDidUpdate(){
console.debug("存在期:componentDidUpdate")
}
render() {
if(!this.props.reRender){
console.debug("实例化:render")
}else{
console.debug("存在期:render")
}
return (
<div>
<br />
请查看下面的console
<br />
</div>
)

}
}
Components.defaultProps = {
text: "hello word",
}
class App extends React.Component{
constructor(props){
super(props);
this.state = {}
}
refresh(){
return (e)=>{
this.setState({
reRender: true,
})
}
}
render(){
return (
<div>
<Components reRender={this.state.reRender}/>
<button onClick={this.refresh()}>
更新Component
</button>
</div>
)
}
}
//这个组件是没有调用的,但是,getDeafultProps直接执行了
var Test = React.createClass({
getDefaultProps: function(){
console.debug("Test组件为调用,直接执行了defaultProps")
return {

}
},
render(){
return (
<div></div>
)
},
})
/*
* Render the above component into the div#app
*/
ReactDOM.render(<App />, document.getElementById('app'));

 


更多专业前端知识,请上【猿2048】www.mk2048.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: