React 函数生命周期基础

1 ,概念

  • 在组件创建、到加载到页面上运行、以及组件被销毁的过程中,总是伴随着各种各样的事件,这些在组件特定时期,触发的事件,统称为组件的生命周期;*

2,组件生命周期分为三部分

  1,在组件创建阶段

    组件创建阶段的生命周期函数,有一个显著的特点:创建阶段生命周期函数在组件的一辈子中,只执行一次;

  2,组件运行阶段

    也有一个显著的特点,根据组件的state和props的改变,有选择性的触发0次或多次;

  3,组件销毁阶段

    也有一个显著的特点,一辈子只执行一次;

 

在程序运行的过程中,会自动执行的函数,被称为生命周期函数

记住常用的生命周期方法

  加载期

    constructor()

    componentWillMount()

    render()

    componentDidMount()

   更新期

    componentWilUpdate()

    render()

    componentDidUpdate()

3,案例部分

 1 import React, { Component } from 'react'
 2 
 3 export class Demo extends Component {
 4     // 初始化数据
 5     constructor(props){
 6         super();
 7         console.log('construtor....在这里初始化数据')
 8         this.state = {
 9             list:[],//从数据库获取的数据
10             num:0,
11             isStart:false
12         }
13     }
14     // 获取数据库数据
15     componentWillMount(){
16         console.log('componentWillMount....在这里使用Ajax获取数据');
17     }
18     // 向页面渲染数据
19     render() {
20         console.log('render....在这里生成DOM');
21         return (
22             <div>
23                 <h3>数据展示:</h3>
24                 <p>
25                 <input type='checkbox' onChange={this.change.bind(this)} />
26                 按钮是否可用
27                 </p>
28                 <button onClick={this.click.bind(this)}>更新数据</button>
29                 <p>数据:{this.state.num}</p>
30             </div>
31         )
32     }
33     // 渲染后执行
34     componentDidMount(){
35         console.log('componentDidMount....向DOM中渲染数据');
36     }
37 
38     //复选框点击事件
39     change(e){
40         this.setState({
41             isStart:e.target.checked
42         })
43     }
44 
45     //按钮点击事件
46     click(){
47         console.log('更新数据....')
48         let i = this.state.num;
49         i++;
50         this.setState({
51             num:i
52         });
53     }
54     // 判断是否更新state数据
55     shouldComponentUpdate(){
56         return this.state.isStart;
57     }
58 
59     // 在组件接收到新的props或者state但还没有render时被调用
60     componentWillUpdate(){
61         console.log('componentWillUpdate....');
62     }
63     // 在组件完成更新后立即调用
64     componentDidUpdate(){
65         console.log('componentDidUpdate.....');
66     }
67 
68 }
69 
70 export default Demo

 

版权声明:本文为gjf-7原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/gjf-7/p/12292467.html