React 组件生命周期

513 阅读1分钟

React生命周期

在组件的整个生命周期中,随着该组件的props或者state发生改变,其DOM表现也会有相应的变化。一个组件就是一个状态机,对于特定地输入,它总返回一致的输出。 一个React组件的生命周期分为三个部分:实例化、存在期和销毁时。

(图片来源:juejin.cn/post/684490…)

初始化阶段

defaultProps

//设置默认props属性
static defaultProps = {
    name: 'web',
    age:23
};

constructor

//构造函数,可以用来配声明tate
constructor() {
    super();
    this.state = {number: 0}
}

componentWillMount

//组件渲染前
componentWillMount(){
    //做一些组建渲染前的操作
}

render

组件渲染

componentDidMount

//组件完成渲染后
conponentDidMount(){
    this.input.focus();
}

运行中

componentWillReceiveProps()

组件接收到属性变化

shouldComponentUpdate()

用来控制state或props改变后是否需要重新render一个虚拟DOM

shouldComponentUpdate(newProps, newState) {
    if (newProps.number < 5) return true;
    return false
}
//该钩子函数可以接收到两个参数,新的属性和状态,返回true/false来控制组件是否需要更新。

componentWillUpdate()

组件即将被更新时触发

componentDidUpdate()

组件被更新后触发,可以进行DOM操作

销毁

componentWillUnmount()

组件将要销毁时的操作