React 组件生命周期

React生命周期

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

(图片来源: juejin.im/post/5a062f…)

初始化阶段

defaultProps

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

constructor

//构造函数,能够用来配声明tate
constructor() {
    super();
    this.state = {number: 0}
}
复制代码

componentWillMount

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

render

组件渲染java

componentDidMount

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

运行中

componentWillReceiveProps()

组件接收到属性变化web

shouldComponentUpdate()

用来控制state或props改变后是否须要从新render一个虚拟DOMbash

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

componentWillUpdate()

组件即将被更新时触发函数

componentDidUpdate()

组件被更新后触发,能够进行DOM操做post

销毁

componentWillUnmount()

组件将要销毁时的操做ui

相关文章
相关标签/搜索