React生命周期

媒介

React组件的生命周期能够分为挂载,衬着和卸载这几个阶段。
当衬着后的组件须要更新时,我们会从新去衬着组件,直至卸载。
因而,能够把React生命周期分红两类:
1.当组件在挂载或卸载时。
2.当组件吸收新的数据时,即组件更新时。

一.挂载或卸载历程

1.组件初始化

static defaultProps保证this.props有初始值
this.state初始值
componentWillMount会在render之前挪用,componentDidMount会在render以后挪用,离别代表了衬着前后的时刻,
都只实行一次。
render以后,我们在componentDidMount中实行setState,组件会再次render,不过在初始化历程就衬着了两次组件
,这并非一件功德,但实际情况是,有些场景不得不须要setState,比方盘算组件的位置或宽高级,就不得不让组件
先衬着,更新必要的信息后,再次衬着。

2.组件的卸载:
componentWillMount,我们常常会实行一些清算要领,如事宜接纳或是消灭定时器。

    componentWillMount() {
        this.setState({
            a: this.state.a + 1    // 先实行willMount,a + 1,再实行render,componentDidMount
        });
        console.log('will' + this.state.a);
    }
    componentDidMount() {
        console.log('did' + this.state.a);
    }
    render() {
        console.log('render' + this.state.a);
        return (
            <div>
                <div><button onClick={ this.add }>home</button></div>
                <div>{ this.state.a }</div>
                <div>{ this.props.maxLoops }</div>
                <About2 id={ this.state.a } />
            </div>
        );
    }

二.数据更新历程

1.数据更新历程:
更新历程指的是父组件向下通报props或组件本身实行setState要领时发作的一系列更新行动。
假如组件本身state更新了,那末会顺次实行shouldComponentUpdate,componentWillUpdate,render和componentDidUpdate。
shouldComponentUpdate是一个迥殊的要领,它接收须要更新的props和state,让开发者增添必要的前提推断,
让其在须要时更新,不须要时不更新。因而,当要领返回false的时刻,组件不再向下实行生命周期要领。
2.父节点props转变
当父节点this.state转变,传入子组件的this.props发作转变,组件会顺次挪用componentWillReceiveProps,
shouldComponentUpdate,componentWillUpdate,render,componentDidUpdate.
子组件会从新衬着。
3.假如组件是由父组件更新props而更新的,那末在shouldComponentUpdate之前会实行componentWillReceiveProps要领,此要领能够作为React在props传入后,衬着之前setState时机,在此要领中setState是不会二次衬着的。

componentWillReceiveProps(nextProps) {
        console.log('willreceive');
        console.log(nextProps);
        if (nextProps.id === 4) {
            this.setState({
                bb: 1000
            })
        }
    }
    shouldComponentUpdate(nextProps, nextState) {
        console.log('should update');
        if (nextState.bb === 16) {
            return false;
        }
        return true;
    }
    componentWillUpdate(nextProps, nextState) {
        console.log('will update');
    }
    componentDidUpdate(prevProps, prevState) {
        console.log('did update');
    }
    原文作者:蛋白
    原文地址: https://segmentfault.com/a/1190000010257486
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞