React组件生命周期详解

React组件生命周期

constructor( ) 构造方法

constructor是ES6对类的默认方法,经过 new 命令生成对象实例时自动调用该方法。而且,该方法是类中必须有的,若是没有显示定义,则会默认添加空的constructor( )方法。当存在constructor的时候⚠️必须手动调用super方法。若是在constructor中想使用this关键字,就必须先调用super方法 MDN-super。 在constructor中若是要访问this.props须要在super中传入props。可是不管有没有定义constructor,super是否传入props参数,在react的其余生命周期中this.props都是可使用的,这是React自动附带的。javascript

class MyClass extends React.component{
    constructor(props){
        super(props); // 声明constructor时必须调用super方法
        console.log(this.props); // 能够正常访问this.props
    }
}
复制代码

constructor 构造方法经常使用来初始化statejava

class MyClass extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            list: this.props.List
        };
        this.state.list = []; //修改state
        setTimeout(() => {
          this.setState({list: [1, 2, 3]}); //异步操做后 setState 触发渲染
        }, 100);
    }
}
复制代码

须要注意的是,在构造函数里定义了state,当你想在一些操做后修改state,只须要直接操做this.state便可, 若是你在构造函数里执行了异步操做,就须要调用setState来触发从新渲染。在其他的地方当你须要改变state的时候只能使用this.setState,这样 React 才会触发刷新UI渲染。node

Class静态方法实例属性 初始化statereact

class ReactCounter extends React.Component {
	state = {
	  list: []
	};
}
复制代码

具体文章可见Class-的静态方法ios

componentWillMount() 组件挂载以前

在组件挂载以前调用且全局只调用一次。若是在这个钩子里能够setState,render后能够看到更新后的state,不会触发重复渲染。该生命周期能够发起异步请求,并setState。(React v16.3后废弃该生命周期,能够在constructor中完成设置statees6

render()  渲染组件

render是一个React组件必须定义的生命周期,用来渲染dom。⚠️不要在render里面修改state,会触发死循环致使栈溢出。render必须返回reactDomaxios

render() {
	const {nodeResultData: {res} = {}} = this.props;
	if (isEmpty(res)) return noDataInfo;
	const nodeResult = this.getNodeResult(res);
	return (
		<div className="workspace-dialog-result"> {nodeResult} </div>
	);
复制代码

componentDidMount() 组件挂载完成后

在组件挂载完成后调用,且全局只调用一次。能够在这里使用refs,获取真实dom元素。该钩子内也能够发起异步请求,并在异步请求中能够进行setState。dom

componentDidMount() {
	axios.get('/auth/getTemplate').then(res => {
		const {TemplateList = []} = res;
		this.setState({TemplateList});
	});
}
复制代码

componentWillReceiveProps (nextProps ) props即将变化以前

props发生变化以及父组件从新渲染时都会触发该生命周期,在该钩子内能够经过参数nextProps获取变化后的props参数,经过this.props访问以前的props。该生命周期内能够进行setState。(React v16.3后废弃该生命周期,能够用新的周期 static getDerivedStateFromProps 代替)异步

shouldComponentUpdate(nextProps, nextState) 是否从新渲染

组件挂载以后,每次调用setState后都会调用shouldComponentUpdate判断是否须要从新渲染组件。默认返回true,须要从新render。返回false则不触发渲染。在比较复杂的应用里,有一些数据的改变并不影响界面展现,能够在这里作判断,优化渲染效率。函数

componentWillUpdate(nextProps, nextState)

shouldComponentUpdate返回true或者调用forceUpdate以后,componentWillUpdate会被调用。不能在该钩子中setState,会触发重复循环。(React v16.3后废弃该生命周期,能够用新的周期 getSnapshotBeforeUpdate)

componentDidUpdate() 完成组件渲染

除了首次render以后调用componentDidMount,其它render结束以后都是调用componentDidUpdate。该钩子内setState有可能会触发重复渲染,须要自行判断,不然会进入死循环。

componentDidUpdate() {
    if(condition) {
        this.setState({..}) // 设置state
    } else {
        // 再也不设置state
    }
}
复制代码

componentWillUnmount() 组件即将被卸载

组件被卸载的时候调用。通常在componentDidMount里面注册的事件须要在这里删除。

生命周期图

完整的生命周期示例

class LifeCycle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {str: "hello"};
    }

    componentWillMount() {
        alert("componentWillMount");
    }

    componentDidMount() {
        alert("componentDidMount");
    }

    componentWillReceiveProps(nextProps) {
        alert("componentWillReceiveProps");
    }

    shouldComponentUpdate() {
        alert("shouldComponentUpdate");
        return true;        // 记得要返回true
    }

    componentWillUpdate() {
        alert("componentWillUpdate");
    }

    componentDidUpdate() {
        alert("componentDidUpdate");
    }

    componentWillUnmount() {
        alert("componentWillUnmount");
    }
	render() {
        alert("render");
        return(
            <div> <span><h2>{parseInt(this.props.num)}</h2></span> <br /> <span><h2>{this.state.str}</h2></span> </div>
        );
    }
}
复制代码

React v16.3 新加入的生命周期 (转载)

react v16.3删掉如下三个生命周期

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate

新增两个生命周期

  • static getDerivedStateFromProps
  • getSnapshotBeforeUpdate

static getDerivedStateFromProps

  • 触发时间:在组件构建以后(虚拟dom以后,实际dom挂载以前) ,以及每次获取新的props以后。
  • 每次接收新的props以后都会返回一个对象做为新的state,返回null则说明不须要更新state.
  • 配合componentDidUpdate,能够覆盖componentWillReceiveProps的全部用法
class Example extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // 没错,这是一个static
  }
}
复制代码

getSnapshotBeforeUpdate

  • 触发时间: update发生的时候,在render以后,在组件dom渲染以前。
  • 返回一个值,做为componentDidUpdate的第三个参数。
  • 配合componentDidUpdate, 能够覆盖componentWillUpdate的全部用法。
class Example extends React.Component {
	getSnapshotBeforeUpdate(prevProps, prevState) {
	// ...
	}
}
复制代码
相关文章
相关标签/搜索