React 生命周期方法对比

1、生命周期方法对比

2、生命周期方法的使用

本文参考·react官方文档:http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

 

1、生命周期方法前后对比图

React 生命周期方法对比_第1张图片React çå½å¨æå¾è§£

相同点:

1)声明周期均划分为 创建、 更新、 销毁三个阶段

2)  常用声明周期方法未变更,如 render、 componentDidMount、 componentDidUpdate、 componentWillUnmount等

不同点:

1) 创建阶段: 旧版本组件构造函数调用完成之后会有componentWillmount方法,新版本省略,新增getDerivedStateFromProps方法(并不常用),且该方法在组件props,state变更时也会被调用

2)更新阶段:  当shouldComponentUpdate返回ture后,会调用rende方法重新渲染组件。在组件更新完成之前有getSnapShotBeforeUpdate方法

 

2、生命周期方法的使用

1)

// constructor作用:
// 1、super(props) 继承父类的属性, 此后可以使用this , this.props
// 2、this.state   初始化state,注意这里对state直接进行赋值操作,其他时候如果需要变更state需要setState(重点)
// 3、事件的绑定:参考官方文档,如何进行事件处理,及事件处理过程中this的绑定https://reactjs.org/docs/handling-events.html

constructor(props){
    super(props)
    this.state = {
        name: 'lei',
        age : 24
    }
    this.handleClick = this.handleClick.bind(this)
}

2)componentDidmount

这个比较常用了,通常在这里处理一些副作用,如请求后端接口。

3)shouldComponentUpdate

//nextProps、 nextState表示更新之后的参数,this.state为未变更时参数
//返回值为ture || false
shouldComponentUpdate(nextProps, nextState) {
    return this.state.name == nextState.name
}

4)componentDidupdate

//接收参数为更新前的props、state
//一般不要在这个生命周期中调用setState,除非有状态判断
//这个生命周期中进行可以获取数据等副作用操作
componentDidUpdate(prevProps, prevState, snapshot){
    if(this.state.name == prevState.name){
        //...
        this.getData();
    }
}

5、componentWillUnMount

在组件被卸载和销毁之前立即调用。在此方法中执行任何必要的清理,例如使计时器无效、取消网络请求或清除在组件

 

你可能感兴趣的:(React)