一个组件完整的生命周期包含实例化阶段、活动阶段、销毁阶段三个阶段。每个阶段又由相应的方法管理。
过程中涉及三个主要的动作术语:
- mounting:表示正在挂接虚拟DOM到真实DOM。
- updating:表示正在被重新渲染。
- unmounting:表示正在将虚拟DOM移除真实DOM。
每个动作术语提供两个函数:
- omponentWillMount()
- componentDidMount()
- componentWillUpdate(object nextProps, object nextState)
- componentDidUpdate(object prevProps, object prevState)
- componentWillUnmount()
实例编写
通过一个简单的实例,来看React组件的生命周期。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>React-props</title>
<script src="./common/react.js"></script>
<script src="./common/react-dom.js"></script>
<script src="http://cdn.bootcss.com/babel-core/5.8.38/browser.min.js"></script>
</head>
<body>
<div id="demo"></div>
<script type="text/babel">
var AddCount=React.createClass({
getInitialState:function(){
console.log('1...getInitialSate');
return {count:1};
},
componentWillMount:function(){
console.log('2...componentWillMount');
},
componentDidMount:function(){
console.log('3...componentDidMount');
},
componentWillUpdate:function(){
console.log('4...componentWillUpdate');
},
componentDidUpdate:function(){
console.log('4...componentDidUpdate');
},
handleClick:function(event){
this.setState({count:this.state.count+1})
},
render:function(){
return(
<p>
{this.state.count}<br/>
<button onClick={this.handleClick}>Add</button>
</p>
)
}
})
ReactDOM.render(
<AddCount/>,
document.getElementById("demo")
);
</script>
</body>
</html>
这个案例在每个生命周期里都加入了输出语句,我们可以打开控制台看代码的执行过程。
👋 感谢您的观看!
© 版权声明
本站网络名称: 微看VCAN网
本站永久网址: https://www.dzq3.com
网站侵权说明: 本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长删除处理。
1 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
2 本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
3 本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。
1 本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
2 本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
3 本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。
THE END
暂无评论内容