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

React组件的生命周期

2017-03-02 11:35 513 查看

React
中组件的生命周期函数,又叫钩子函数

React
的生命周期分两类来说明

一、从组件的一般挂载与卸载的过程来分

二、从组件数据更新过程来划分

从组件的一般挂载与卸载的过程来分 :

constructor
ES6
创建方式中的构造函数,在组件实例化的时候就会调用,创建组件的时候会默认添加
constructor
函数,如果你要添加
state
状态等的就要手动添加,不然可以省去。

componentWillMount
组件渲染前调用的钩子函数,一般在这个钩子函数里面设置
state
或者请求数据给
state
赋值

render
渲染组件的钩子函数,可以说是每个组件都要用的钩子函数(无状态组件)直接
return


componentDidMount
组件渲染之后调用的钩子函数。一般用处:获取真实的DOM元素节点(原生js操作DOM),进行DOM操作

componentWillUnmount
组件卸载的时候调用的钩子函数。一般作用在
componentDidMount
钩子函数中进行的事件绑定的移除。

code代码见下面

import React, {Component} from 'react';
export default class App extends Component {
constructor(props) {
super(props);
console.time();
console.log('我是constructor方法');
console.timeEnd();
}
//组件渲染前
componentWillMount() {
console.time();
console.log('我是componentWillMount方法');
console.timeEnd();
}
render() {
console.time();
console.log('我是render方法')
console.timeEnd();
return (
<div></div>
)
}
//组件渲染之后
componentDidMount() {
console.time();
console.log('我是componentDidMount方法');
console.timeEnd();
//console.log(dom);
}
componentWillUnmount(){
console.log("组件卸载");
}
}


在浏览器中运行结果



从组件数据更新过程来划分(前提先抛开上面的根据过程的生命周期)

componentWillReceiveProps(nextProps)
获取父组件才会执行的钩子函数

shouldComponentUpdate(nextProps,nextState)
重新设置
state
的值的时候就会调用,在默认情况下,
showComponentUpdate
函数都返回true

componentWillUpdate
在组件渲染前调用

componentDidUpdate
在组件渲染之后调用

代码详见

import React, {Component} from 'react';
import {getJson} from './Utils';
export default class App extends Component {
constructor(props) {
super(props);
console.time();
console.log('我是constructor方法');
console.timeEnd();
this.state= {
data:''
}
}
//组件挂载之前的
componentWillMount() {
console.time();
console.log('我是componentWillMount方法');
console.timeEnd();
//getJson是自己封装的fetch请求的数据方式
getJson('http://www.xxxxx.com/mobile.php?c=Product&a=category',(response)=>{
let {errmsg,data} = response;
if(errmsg == '成功'){
this.setState({
data:data
})
}
})
}
//父组件更新props的时候子组件会优先shouldComponentUpdate前调用componentWillReceiveProps钩子函数
componentWillReceiveProps(nextProps){
console.log(`我是componentWillReceiveProps函数--${nextProps}`);
return true;
}
//setState后都会调用shouldComponentUpdate判断是否需要重新
shouldComponentUpdate(nextProps,nextState){
console.log(`我是shouldComponentUpdate函数--${nextProps}---${nextState}`);
//console.log(JSON.stringify(nextProps))
return true;
}
//shouldComponentUpdate返回true或者调用forceUpdate之后
componentWillUpdate(nextProps,nextState){
console.log(`我是componentWillUpdate函数--${nextProps}---${nextState}`);
return true;
}
c
4000
omponentDidUpdate(nextProps,nextState){
console.log(`我是componentDidUpdate函数--${nextProps}---${nextState}`);
return true;
}
render() {
console.time();
console.log('我是render方法')
console.timeEnd();
return (
<div></div>
)
}
}


运行结果如下图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: