react的生命周期-07

2019-12-10  本文已影响0人  逝去丶浅秋

reace生命周期函数:组件加载之前,组件加载完成,组件更新数据,及组件销毁时触发的一系列的方法。

1、组件加载触发的函数:

constructor:构造函数
componentWillMount:组件将要挂载时触发
render:数据渲染
componentDidMount:组件挂载完成时触发,但并不会重新渲染

import React from 'react';

class LifeCycle extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            msg:'lifeCycle的msg'
         };
         console.log("构造函数执行--->"+this.state.msg)
    }
    componentWillMount(){
        console.log("组件将要挂载--->componentWillMount方法执行")
    }
    componentDidMount(){
        console.log("组件挂载完成--->componentDidMount方法执行")
    }

    render() {
        console.log("数据渲染--->render方法执行")
        return (
            <div>
                <h2>react生命周期</h2>
            </div>
        );
    }

}

export default LifeCycle;

执行的结果:

构造函数执行--->lifeCycle的msg
组件将要挂载--->componentWillMount方法执行
数据渲染--->render方法执行
组件挂载完成--->componentDidMount方法执行
2、组件更新触发的函数:

shouldComponentUpdate:组件是否需要更新
componentWillUpdate:组件将要更新
render:渲染数据
componentDidUpdate:组件更新完成

shouldComponentUpdate(msg){
    if(this.state.msg !== msg){
        console.log("组件需要更新--->shouldComponentUpdate方法执行")
        return true;
    }
    return false;
}
componentWillUpdate(){
    console.log("组件将要更新--->componentWillUpdate方法执行")
}
componentDidUpdate(){
    console.log("组件更新完成--->componentDidUpdate方法执行")
}

对于shouldComponentUpdate这个方法,如果你的组件中的值改变才需要更新时,你可以使用shouldComponentUpdate来进行检查,这个方法返回true时,react才会去渲染这个组件,当返回false时,就会被调停,不去渲染。

//官方文档里的例子
shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
        return true;
    }
    if (this.state.count !== nextState.count) {
        return true;
    }
    return false;
}

这个方法中的两个参数nextState和nextProps,这两个参数是构造函数中改变后的state和props的值。

执行结果:

组件需要更新--->shouldComponentUpdate方法执行
组件将要更新--->componentWillUpdate方法执行
数据渲染--->render方法执行
组件更新完成--->componentDidUpdate方法执行

ps:!=和!==的区别:
!==:同类型才会比较;
!=:类型不同会尝试转换类型
两者都是比较值。

3、组件卸载触发的函数:

componentWillUnmount:组件卸载时触发

App.js
constructor(props){
    super(props);
    this.state={
        flag:true
    }
}
//点击对flag取反来改变状态,默认为挂载
setFlag=()=>{
    this.setState({
        flag:!this.state.flag
    })
}
{
    this.state.flag?<LifeCycle/>:""
}
<button onClick={this.setFlag}>挂载或卸载</button>

执行结果如下:

第一次点击:
    组件卸载--->componentWillUnmount方法执行
第二次点击:
    构造函数执行--->lifeCycle的msg
    组件将要挂载--->componentWillMount方法执行
    数据渲染--->render方法执行
    组件挂载完成--->componentDidMount方法执行

当检测到组件卸载后就会调用,组件挂载时又会触发挂载时的函数。

4、在父组件里面改变props传值触发的函数:

componentWillReceiveProps:父组件props值改变时触发

App.js
constructor(props){
    super(props);
    this.state={
        title:"aaa"
    }
}
setTitle=()=>{
    this.setState({
        title:"bbb"
    })
}

<button onClick={this.setTitle}>改变props值</button>
LifeCycle.js
componentWillReceiveProps(){
    console.log("父组件中props的值被改变--->componentWillReceiveProps方法执行")
}

执行结果如下:

父组件中props的值被改变--->componentWillReceiveProps方法执行

写在最后:

上一篇下一篇

猜你喜欢

热点阅读