React中生命周期钩子函数实例演示

    技术2022-07-10  98

    生命周期钩子函数速查表 

    # React生命周期钩子函数 ## 页面渲染期 * constructor 构造函数 在所有函数执行之前它先执行(数据接收 实现继承super(props)) * UNSAFE_componentWillMount 组件将要挂载(数据挂载之前 可以操作数据 不可以操作dom) * render 页面渲染(渲染组件 和 html 标签) * componentDidMount 组件挂载完成(数据挂载之后 可以操作数据和dom) ## 页面更新期 * UNSAFE_componentWillReceiveProps 父组件上状态变化时 会自动触发钩子函数 子组件可以由此决定是否接收数据(接收组件传入输入数据) * shouldComponentUpdate 组件是否要更新数据,需要返回布尔值 true 跟新数据 false 不更新数据(检测组件内的变化 可以用作页面性能的优化(默认值为true)) * UNSAFE_componentWillUpdate 组件更新数据(组件更新之前调用) * render 页面从新渲染(组件更新之后渲染组件) * componentDidUpdate 组件数据更新完成(组件更新之后调用) ## 页面销毁期 * componentWillUnmount 页面销毁(组件销毁时调用 可以做一些内存的优化 [全局变量,闭包,计时器,事件])

    只有类组件才有生命周期,函数组件没有生命周期

    生命周期

    父组件

    // 父组件 import React,{ Component } from 'react' import Child from './child' // 钩子函数执行顺序和编写顺序无关 export default class Parent extends Component{ // 页面渲染期 constructor(){ super() this.state = { msg:'', showChild:true } console.log('构造函数执行了-constructor...') } // 严格模式下 不建议使用 UNSAFE_componentWillMount(){ console.log('组件将要挂载-componentWillMount...'); } render(){ console.log('页面渲染了-render...'); let el = this.state.showChild ? <Child msg={ this.state.msg }/> : null return( <div> <h1>parent组件</h1> <input type="text" value={this.state.msg} onChange={ (e)=>this.msgChange(e) } /> <p>{ this.state.msg }</p> <button onClick={ ()=>this.setState({showChild:!this.state.showChild}) }>销毁</button> <hr/> {el} </div> ) } componentDidMount(){ console.log('组件挂载完成-componentDidMount...'); } // 页面更新期 shouldComponentUpdate(){ console.log('=================') console.log('组件是否要更新数据吗?-shouldComponentUpdate...') // 返回true 可以更新数据 false 不更新数据 return true; } UNSAFE_componentWillUpdate(){ console.log('组件将要更新数据-componentWillUpdate...') } msgChange(e){ // 更新数据 console.log('数据正在更新中...') this.setState({ msg:e.target.value }) } // 还有个 render钩子函数 页面渲染 componentDidUpdate(){ console.log('组件数据更新完成-componentDidUpdate...') } }

    子组件

    // 子组件 import React, { Component } from 'react' export default class Child extends Component { // 渲染期 constructor() { super() console.log('子组件构造函数执行...') } render() { console.log('子组件渲染了...') return ( <div> <h1>child子组件</h1> <p>接收到父组件数据:{this.props.msg}</p> </div> ) } UNSAFE_componentWillMount() { console.log('子组件将要挂载...') } componentDidMount() { console.log('子组件挂载完成...') } // 更新期 shouldComponentUpdate() { console.log('子组件是否要更新数据?...') return true } UNSAFE_componentWillUpdate() { console.log('子组件将要更新数据...') } componentDidUpdate() { console.log('子组件数据更新完成...') } // 放子组件 会自动执行 放父组件不会自动执行 UNSAFE_componentWillReceiveProps() { console.log('子组件将要接收父组件传递的数据...') } // 页面销毁期 componentWillUnmount(){ console.log('子组件将要被销毁...') } }

    GIF演示

     

    Processed: 0.014, SQL: 12