生命周期
分为三个阶段:挂载,渲染,卸载
1.componentWillMount 挂载时触发
变量和函数已经生成,但是虚拟dom还没有渲染到页面
2.constructor 构造函数
用来定义变量,接收父类传值,改变函数this指向等
3.render 生成dom渲染
把虚拟dom转化为页面标签渲染
4.componentDidMount 挂载后触发
表示第一次渲染完成,此时虚拟dom已经生成
5.shouldComponentUpdate 更新中
主要做线程优化,可以设置线程安全,或者阻止更新,rerurn false不更新
6.componentWillReciveProps 更新前
接收变量的新旧值,进行判断和对比
7.componentDidUpdate 更新后
此时props和state已经改变完毕,可以把变量进行后续处理
8.componentWillUnmount 卸载
可以在组件下删除变量或函数,清空周期函数等
练习:动态时钟
- <body>
- <div id="app"></div>
- <script type="text/babel">
- class App extends React.Component{
- constructor(props){
- super(props)
- this.state={date:new Date()}
- }
- fun(){
- this.setState({date:new Date()})
- }
- componentWillUnmount(){
- clearInterval(this.th)
- }
- componentWillMount(){
- this.th=setInterval(()=>{
- this.fun()
- },1000)
- }
- render(){
- return <h1>{this.state.date.toLocaleTimeString()}</h1>
- }
- }
- ReactDOM.render(
- (<div>
- <App />
- </div>),
- document.getElementById("app")
- )
- </script>
- </body>