react生命周期详解

          class Wrap extends React.Component{
            render(){
                return <div className="wrap" style={{background:'skyblue'}}>
                            wrap
                            <p>{this.props.name}</p>
                        </div>
            }
            componentWillReceiveProps(nextProps){//组件将要接受props变化
                console.log('componentWillReceiveProps')
            }
            shouldComponentUpdate(nextProps,nextState){
                console.log('wrap-shouldComponentUpdate')
                return false;
            }
            componentWillUnmount(){
                console.log('componentWillUnmount')
            }
        }
        class Container extends React.Component{
            //组件被创建时首先执行  可以接收props 可以定义state 
            constructor(props){
                super(props)
                this.state={
                    name:'凌晨两点半',
                    open:true
                }
                console.log('constructor')
                console.log(this)
            }
            //可以重新设置 state
            componentWillMount(){
                console.log('componentWillMount')
                console.log(this.refs.container)
                console.log(this)
            }
            render(){ //渲染真实DOM节点   数据改变是也会执行  
            console.log('render')
                return <div className='container' ref='container'>
                        <div style={{background:'pink'}}>
                        container
                        <p>{this.state.name}</p>
                        <button onClick={()=>{this.setState({name:'me'})}}>setName</button>
                       <button onClick={()=>{this.setState({open:false})}}>卸载</button>
                    </div>
                    {this.state.open?<Wrap name={this.state.name}/>:<div></div>}
                    </div>
            }
            componentDidMount(){//初始化DOM节点已经创建完成  1
                console.log('componentDidMount')
                console.log(this.refs.container)
                console.log('初始化DOM节点已经创建完成')
            }
            //组件状态发生改变应该更新组件
            //必须要设置return  true继续执行 false终止更新  不会往下执行
            shouldComponentUpdate(nextProps,nextState){//如果不调用该函数 默认是true
                console.log('shouldComponentUpdate')
                return true;
            }
            componentWillUpdate(nextProps,nextState){//即将要更新组件
                console.log('componentWillUpdate')
            }
            componentDidUpdate(nextProps,nextState){//组件更新完成
                console.log('componentDidUpdate')
                console.log(nextState,nextProps)
            }
        }
        ReactDOM.render(<Container />,document.querySelector('#app'))
  • 初始创建完成
    react生命周期详解
  • 改变数据后
    react生命周期详解
  • 小结
  • react生命周期详解