react中组件的生命周期函数

react中组件的生命周期函数主要分为三个阶段,分别为:

1. 初始化阶段: 由ReactDOM.render()触发---初次渲染

           1.  constructor()

           2.  componentWillMount()

           3.  render()

           4.  componentDidMount() =====> 常用

           一般在这个钩子中做一些初始化的事,例如:开启定时器、发送网络请求、订阅消息

2. 更新阶段: 由组件内部this.setSate()或父组件render触发

           1.  shouldComponentUpdate()

           2.  componentWillUpdate()

           3.  render() =====> 必须使用的一个

           4.  componentDidUpdate()

3. 卸载组件: 由ReactDOM.unmountComponentAtNode()触发

            1.  componentWillUnmount()  =====> 常用

            一般在这个钩子中做一些收尾的事,例如:关闭定时器、取消订阅消息

旧的生命周期:

react中组件的生命周期函数_第1张图片

我们可以通过写一个demo来看一下

react中组件的生命周期函数_第2张图片

 组件A为父组件,组件B为子组件。点击换车按钮五菱宏光换成一辆GTR。

在各生命周期函数执行时打印一下,看一下执行顺序。

具体代码如下:

组件A

import React, { Component } from 'react'
import HookB from './hookB'

export default class hookA extends Component {

    state = {
        carName:'五菱宏光'
    }

    constructor(){
        super()
        console.log('A...constructor...');
    }

    //组件挂在前触发
    componentWillMount(){
        console.log('A...componentWillMount....');
    }

    // 组件挂载后触发
    componentDidMount(){
        console.log('A...componentDidMount...');
    }

    //点击事件
    changeCar = () => {
        this.setState({ carName : 'GTR'  })
        //得漂得漂得咿的漂
    }

    render() {
        console.log('A...render');
        return (
            
我是组件A
) } }

组件B

import React, { Component } from 'react'

export default class hookB extends Component {

    constructor(){
        super()
        console.log('B...constructor...');
    }

    //组件挂载前触发
    componentWillMount(){
        console.log('B...componentWillMount....');
    }
    //组件挂载后触发
    componentDidMount(){
        console.log('B....componentDidMount...');
    }
    //组件接收到新的props时触发
    componentWillReceiveProps(props){
        console.log('componentWillReceiveProps....');
    }
    //页面是否应该更新
    //true:更新,false:不更新
    shouldComponentUpdate(){
        console.log('shouldComponentUpdate...');
        return true
    }

    //更新前触发
    componentWillUpdate(){
        console.log('componentWillUpdate....');
    }
    //更新后触发
    componentDidUpdate(){
        console.log('componentDidUpdate....');
    }
    //卸载前触发
    componentWillUnmount(){
        console.log('componentWillUnmount....');
    }

    render() {
        console.log('B...render');
        return (
            
组件B要换一辆:{ this.props.carName}
) } }

控制台打印如下:

点击切换按钮前

react中组件的生命周期函数_第3张图片

 点击切换按钮后 

react中组件的生命周期函数_第4张图片

 

你可能感兴趣的:(react,react)