React生命周期函数

630 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

定义

生命周期函数:生命周期函数指的是组件在某一时刻会自动执行的函数

React生命周期函数:在React中,生命周期函数指的是组件在某一时刻会自动执行的函数

React生命周期

基本上可以分为以下几个周期

  • Initialization:组件初始化过程
  • Mounting:页面挂载过程
  • Updating:更新过程
  • Unmounting:卸载过程

React生命周期函数有哪些

挂载: 1.constructor():在初始化页面的过程中调用

constructor(props) {
    //...
}

2.componentWillMount():在组件已经被渲染到 DOM 前后运行

// 挂在前自动执行
    componentWillMount() {
        console.log('componentWillMount');
    }

3.render():必须的钩子函数,不应该改变组件的状态

// 渲染时自动执行
    render() {
        console.log('render')
    }

4.componentDidMount():在组件已经被渲染到 DOM 中后运行

// 挂在后自动执行
    componentDidMount() {
        console.log('componentDidMount');
    }

在这里插入图片描述

组件更新: 1.componentDidMount():挂载了的组件接收到新属性前调用。

// 挂在后自动执行
    componentDidMount() {
        console.log('componentDidMount');
    }

2.shouldComponentUpdate():在挂载了的组件属性变化和状态变化时调用,通过控制返回的boolean值告诉React是否重新渲染该组件。

// 组件更新前 前自动执行
    shouldComponentUpdate() {
        console.log('shouldComponentUpdate');
        return true;
    }

3.shouldComponentUpdate():接收到新属性或状态时在渲染shouldComponentUpdate后调用

// 组件更新前 shouldComponentUpdate之后 自动执行
    componentWillUpdate() {
        console.log('componentWillUpdate');
    }

4.componentDidUpdate():在更新发生后立即被调用

// 组件更新前 render 自动执行
    componentDidUpdate() {
        console.log('componentDidUpdate');
    }

在这里插入图片描述 卸载: 1.componentWillUnmount():在组件从 DOM 中移除之前立刻被调用

// 组件从页面中移除前自动执行
	componentWillUnmount() {
		console.log('componentWillUnmount');
	}

\