想了解更多—> 上一篇文章:React入门(一):第一个React应用程序
序言:
- 一、组件的生命周期
- 二、过程和说明
- 三、实战举例
一、组件的生命周期
componentWillMount
componentDidMount
componentWillUnmount
componentWillUpdate
componentDidUpdate
shouldComponentUpdate
componentWillReceiveProps
二、过程和说明
React组件的生命周期,分三个阶段:Mounted、Update、Unmounted。接下面过程和图片。
过程:
- 我们从浏览器上看到从无到有的效果,Mounted已经结束了。
- Update:当React的Component的stated确实改变了更新了,React的Component就会被重新render的过程就是Update。
- Unmounted:一个mounted的React Components对应的DOM节点被从DOM结构中移除的这样一个过程。
说明:
- 每一个状态React都封装了对应的hook函数。
- props一般设置了不会变的,state可变的;props专情,state花心。
<div style={{opacity: this.state.opacity, fontSize: this.state.fontSize}}></div>
三、实战举例
话不多说上代码,有详细解释,如下:
<!--
组件的生命周期:
componentWillMount
componentDidMount
componentWillUnmount
componentWillUpdate
componentDidUpdate
shouldComponentUpdate
componentWillReceiveProps
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Component life circle</title>
<script src="https://cdn.bootcss.com/react/15.4.2/react.min.js"></script>
<script src="https://cdn.bootcss.com/react/15.4.2/react-dom.min.js"></script>
<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.min.js"></script>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
var destination = document.querySelector("#container");
var CounterParent = React.createClass({
// 函数getDefaultProps:在组件加载前被调用
getDefaultProps : function(){
console.log("getDefaultProps: receive props from outsize");
return {};//返回一个空的对象,这个对象实际上对应的是这个组件的props对象(this.props;)。
},
getInitialState: function(){
console.log("getInitialState: set default state of object");
return {};//返回一个空的对象,这个对象实际上对应的是这个组件的state对象(this.state;)。
},
//在组件CounterParent要挂载到container节点之前,就会先调用componentWillMount
// 调用之后,react框架会将这个组件对象CounterParent挂载到container节点上。
componentWillMount: function() {
console.log("componentWillMount: component will about to mount");
return;
},
// 当节点CounterParent被加载到指定的dom节点container之后,执行的函数
// 该函数之后,这个组件对象已经被成功的加载到页面里面去了。
componentDidMount: function(){
console.log("componentDidMount: component is just mount");
return;
},
render: function(){
var s = "CountParent renderring...";
return (
<div>{s}</div>
);
}
})
ReactDOM.render(
<div>
<CounterParent/>
</div>,
destination
);
</script>
</body>
</html>
运行结果:
最后,大家如果发现我写的有错误的话,欢迎评论指出哦,共同进步。
觉得我写的不错的,可以关注下哦^v^。
看完不过瘾,看下一篇文章~
下一篇文章:React入门(三):React State(状态)