链接:http://blog.csdn.net/ElinaVampire/article/details/51813677
getDefaultProps:
getDefaultProps(){return {apple:2}}
负责设置默认的props,这个方法在对象被创建之前执行,因此不能在方法内调用this.props ,另外,注意任何getDefaultProps()返回的对象在实例中共享,不是复制。
getInitialState
一般state会在construct()中初始化。
控件加载之前执行,返回值会被用于state的初始化值
在初次render前后触发:
render
render()方法是很纯净的,这就意味着不要在这个方法里初始化组件的state
componentDidMount
在初始化render之后只执行一次。
从这个函数开始,就可以和 JS 其他框架交互了,例如设置计时 setTimeout 或者 setInterval,或者发起网络请求。
更新props/state时是否需要渲染组件:(如果需要渲染的数据量少则会拖后腿)
shouldComponentUpdate
这个方法在初始化render时不会执行,当props或者state发生变化时执行,并且是在render之前,当新的props或者state不需要更新组件时,返回false。
shouldComponentUpdate: function(nextProps, nextState) {
return nextProps.id !== this.props.id;
}
组件更新前后:
componentWillUpdate
componentWillUnmount() {
clearInterval(this.timerID);
}
当props和state发生变化时执行,并且在render方法之前执行,当然初始化render时不执行该方法,需要特别注意的是,在这个函数里面,你就不能使用this.setState来修改状态。这个函数调用之后,就会把nextProps和nextState分别设置到this.props和this.state中。紧接着这个函数,就会调用render()来更新界面了
componentDidUpdate
componentDidMount() {
........
}
组件更新结束之后执行,在初始化render时不执行
componentWillReceiveProps
当props发生变化时执行,初始化render时不执行,在这个回调函数里面,你可以根据属性的变化,通过调用this.setState()来更新你的组件状态,旧的属性还是可以通过this.props来获取,这里调用更新状态是安全的,并不会触发额外的render调用
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
组件搭建前后
componentWillUnmount
当组件要被从界面上移除的时候,就会调用componentWillUnmount(),在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等。
componentWillMount
执行一次,在初始化render之前执行,如果在这个方法内调用setState,render()知道state发生变化,并且只执行一次。
建议与注意事项:
最后: 建议在componentWillMount,componentDidMount,componentWillReceiveProps方法中修改state值
如果在shouldComponentUpdate和componentWillUpdate中调用了setState,此时this._pendingStateQueue != null,则performUpdateIfNecessary方法就会调用updateComponent方法进行组件更新。但是updateComponent方法又会调用shouldComponentUpdate和componentWillUpdate,因此造成循环调用,使得浏览器内存占满后崩溃。