react的生命周期函数

先来了解一下react的生命周期函数有哪些:

组件将要挂载时触发的函数:componentWillMount
组件挂载完成时触发的函数:componentDidMount
是否要更新数据时触发的函数:shouldComponentUpdate
将要更新数据时触发的函数:componentWillUpdate
数据更新完成时触发的函数:componentDidUpdate
组件将要销毁时触发的函数:componentWillUnmount
父组件中改变了props传值时触发的函数:componentWillReceiveProps

一.挂载部分
根据官方生命周期图我们可以看到,一个组件的加载渲染,首先是defaultProps和propsTypes,(这两个是什么下一篇会单独说,这里也不是重点)
然后就是constructor及this.state里的初始数据,所以到这里是第一步。接着就是componentWillMount 组件将要开始挂载了,这是第二步。然后组件挂载,render解析渲染,所以第三步呼之欲出,就是render数据都渲染完成,最后componentDidMount
组件挂载完成。
子组件代码,父组件内引入渲染即可

import React, { Component } from 'react'

class Smzq extends Component {
    constructor(props) {
        super(props)
        this.state = {
            msg: '我是一个msg数据'
        }
    }
    //组件将要挂载时候触发的生命周期函数
    componentWillMount() {
        console.log('02组件将要挂载')
    }
    //组件挂载完成时候触发的生命周期函数
    componentDidMount() {
        //Dom操作,请求数据放在这个里面
        console.log('04组件挂载完成')
    }
    //是否要更新数据,如果返回true才会更新数据
    shouldComponentUpdate(nextProps, nextState) {
        console.log('01是否要更新数据')
        console.log(nextProps)      //父组件传给子组件的值,这里没有会显示空
        console.log(nextState)      //数据更新后的值
        return true;                //返回true,确认更新
    }
    //将要更新数据的时候触发的
    componentWillUpdate() {
        console.log('02组件将要更新')
    }
    //更新数据时候触发的生命周期函数
    componentDidUpdate() {
        console.log('04组件更新完成')
    }
    //你在父组件里面改变props传值的时候触发的函数
    componentWillReceiveProps() {
        console.log('父子组件传值,父组件里面改变了props的值触发的方法')
    }
    setMsg() {
        this.setState({
            msg: '我是改变后的msg数据'
        })
    }
    //组件将要销毁的时候触发的生命周期函数,用在组件销毁的时候执行操作
    componentWillUnmount() {
        console.log('组件销毁了')
    }
    render() {
        console.log('03数据渲染render')
        return (
            <div>
                生命周期函数演示--{this.state.msg}--{this.props.title}
                <br />
                <hr />
                <button onClick={() => this.setMsg()}>更新msg的数据</button>
            </div>
        )
    }
}
export default Smzq
父组件代码:
import React, { Component } from 'react';
import Smzq from './data2/datachange'

class App extends Component {
    constructor(props){
        super(props)
        this.state={
            flag:true,
            title:"我是app组件的标题"
        }
    }
    //创建/销毁组件
    setFlag(){
        this.setState({
            flag:!this.state.flag
        })
    }
    //改变title
    setTitle(){
        this.setState({
            title:'我是app组件改变后的title'
        })
    }
    render() {
        return (
          <div className="App">
                {
                    this.state.flag?<Smzq title={this.state.title}/>:''
                }
                <button onClick={()=>this.setFlag()}>挂载/销毁生命周期函数组件</button>
                <button onClick={()=>this.setTitle()}>改变app组件的title</button>
          </div>
        );
    }
}
export default App;
 
文章摘自 https://blog.csdn.net/weixin_43851769/article/details/88188325
原文地址:https://www.cnblogs.com/zhx119/p/14653558.html