1.装载过程
当组件第一次被渲染的时候,依次调用的钩子函数如下:
- constructor
constructor ,也就是es6中每个类的构造函数,要创建一个类的实例,就要调用相应的构造函数。
存在的意义:
(1).初始化state
(2).绑定成员函数的this环境
constructor(props) {
super(props);
this.state = {name:'小明',age:20}; //初始化state
this.clickMe = this.clickMe.bind(this,this.state.name); //绑定成员函数的this环境
}
- getInitialState
这个函数里的返回值会用来初始化组件内的this.state,不过只有在React.createClass创建的组件类下才会发生作用,示例如下:
getInitialState: function(){
return {name: '小明'}
}
新版的es6创建方法如下:
class Item extends Component {
constructor(props) {
super(props);
this.state = {name:'小明'}
}
}
- getDefaultProps
这个函数里的返回值可以作为prop的初始值
getDefaultProps: function (){
retrun {name: '小明'}
}
es6使用方法如下:
class Item extends Component {
constructor(props) {
super(props);
this.state = {name:'小明'}
}
}
Item.defaultProps = {
return {name:'小明'}
}
-
componentWillMount
这个函数只会在render函数前调用 -
render
react中最重要的函数,其他函数可以不存在,但是它必须要存在。
通常一个组件要发挥作用,总是要渲染一些东西,render函数并不做实际的渲染工作,只是返回一个jsx的结构,最终由react来操作渲染过程
render() {
return (
<div>
</div>
)
}
- conponentDidMount
只会在render函数后调用
2.更新过程
当组件被挂在到dom数上以后,用户可以在网页上看到组件的第一印象,但是为了提供更好的体验,就要让组件随着用户的操作不断改变,当prop和state改变时,就会引发组件的更新过程
- conponentWillReceiveProps
只要父组件的render函数被调用,在render函数里的子组件就会触发更新过程,不管传递的prop有没有发生改变,都会触发子组件中的conponentWillReceiveProps函数 - shouldComponentUpdate(nextProps,nextState)
除了render函数, shouldComponentUpdate可能是react当中最重要的一个函数了。
render函数决定了组件要渲染什么,而 shouldComponentUpdate函数则决定了一个组件什么时候不需要渲染。
render函数和shouldComponentUpdate函数是react中唯二需要返回结果的函数,render函数的返回结果用于构造dom结构,shouldComponentUpdate函数返回一个布尔值,告诉react组件库在这次更新过程中是否要继续。
在更新过程中,react组件库首先调用shouldComponentUpdate这个函数,如果返回true则继续执行更细过程,接下来调用render函数;反之,如果得到一个false则立刻停止更新过程,也不会引发后续的渲染了。
如果在非常复杂的项目中,这种方法可以大大提高应用的性能
//现在,只有prop中的name改变或者state中的name改变,才会引发渲染操作
shouldComponentUpdate(nextProps,nextState) {
return (nextProps.name !== this.props.name) || (nextState !== this.state.name);
}
- componentWillUpdate
当shouldComponentUpdate返回true,才会执行componentWillUpdate,componentWillUpdate在render函数之前执行 - render
- componentDidUpdate
当shouldComponentUpdate返回true,才会执行componentDidUpdate,componentDidUpdate在render函数之后执行
3.卸载过程
- componentWIllUnmount
react的组件卸载过程只涉及一个componentWIllUnmount函数,当react组件要从dom树上删除之前,对应的componentWIllUnmount就会被执行,所以这个函数适合做一些清理性的工作。