React生命周期

时间:2021-11-14 11:33:26

在react生命周期中,分2段执行,一个挂载的生命周期,一个是组件发生了数据变动,或者事件触发而引发的更新生命周期。

注:react生命周期很重要,对于很多组件场景的应用发挥重要作用,而且不熟悉生命周期之间的调用,mixins混合则玩不来

先从初始化执行开始:

挂载生命周期:

官方提供了componentWillMount,和componentDidMount

componentWillMount:

使用于render渲染组件之前调用,比如当前组件内部值需要发生逻辑上的变化,就可以在此做操作,这样的好处是不用再次render渲染组件。

componentDidMount:

使用于render渲染组件之后调用,比如ajax

var ReactWeek = React.createClass({
getInitialState:function(){
return console.log("getInitialState");
},
getDefaultProps:function(){
return console.log("getDefaultProps");
},
componentWillMount:function(){
console.log("componentWillMount");
},
componentDidMount:function(){
console.log("componentDidMount");
},
render:function(){
return(
<i></i>
)
}
}); React.render(<ReactWeek />,document.body);

这里添加了设置默认值getDefaultProps和初始化设置的getInitialState,运行一下看看它们之间的运行顺序。结果如下

React生命周期