父组件更新时(子组件props变更),子组件会先调用componentWillReceiveProps方法,然后执行的生命周期顺序和子组件state变更一样
react组件的生命周期
props被变更时,会触发一系列的周期。
首先,第一个被调用的生命周期函数是:
componentWillReceiveProps: function(newProps){ } : 返回写return就OK。
接下来被调用的函数与上一节类似,顺序如下:
shouldcomponentUpdate
componentWillUpdate
render
componentDidUpdate
1、创建组件
React.createClass({
getInitialState: function(){
return {};
},
render: function(){
const styleJson = {
color: red;
fontSize: 14;
}
return (
<div style={styleJson }>my component<div>
)
}
})
2、挂载react实例
ReactDom.render({
<div>my app</div>,
destination
})
3、组件返回jsx
render: function(){}
当父组件调用了render函数会触发子组件也调用render函数
4、组件被渲染之前
this.getInitialState()
5、组件被render之前
this.componentDidMount()
6、状态管理
6.1设置状态
this.state = {}
6.2 this.getDefaultProps() 对应this.props对象
6.3修改状态
this.setState()
7、组件样式对象
styleJson = {
color: red;
fontSize: 14;
}
使用样式
<myComponent style={stylejson} />
8、生命周期
8.1组件被挂载到容器之前
this.componentWillMount()
8.2组件被渲染到容器中
ReactDom.render()
8.3组件被成功挂载到容器之后
this.componentDidMount()
this.componentWillMount -》 this.render() -> this.componentDidMount()
8.4当数据变化时,判断属性或者状态改变是否满足更新条件,this.shouldComponentUpdate()第一个被调用
shouldComponentUpdate: function(props, newState){
if(..){
return true
} else {
// 将组件从dom中销毁
ReactDom.unmountComponentAtNode(destination);
return false;
}
}
8.5更新之前
this.componentWillUpdate()
8.6更新之后
this.componentDidUpdate()
8.7组件被销毁前最后一次通知
this.componentWillUnmount()
8.8当组件属性更改之后调用的生命周期
componentWillReceiveProps: function(newProps){}
改变属性调用生命周期比改变state时多了this.componentWillReceiveProps()