react生命周期

2018-07-09  本文已影响0人  peroLuo
// 生命周期函数
import React, {Component} from 'react'
class Live extends Component{
    constructor(props){
        super(props)
        this.state = {
            date: '222'
        }
    }
    componentWillMount(){
         /*
         * 建议在这进行数据初始化,dom树还没渲染
         * */
         console.log('dom将会渲染')
    }
    componentDidMount(){
        console.log('组件已渲染')
    }
    componentWillReceiveProps(nextProps){
        console.log(nextProps)
        console.log('props.name的值发生改变')
    }
    shouldComponentUpdate(nextProps, nextState){
        console.log(this.props.name)
        console.log(nextProps,nextState)
        /*
        * react性能优化非常重要的一环。
        * 组件接受新的state或者props时调用,
        * 我们可以设置在此对比前后两个props和state是否相同,
        * 如果相同则返回false阻止更新,
        * 因为相同的属性状态一定会生成相同的dom树,
        * 这样就不需要创造新的dom树和旧的dom树进行diff算法对比,
        * 节省大量性能,尤其是在dom结构复杂的时候
        * */
        // 返回true则更新数据,false不更新视图
        return true
    }
    componentDidUpdate(){
        /*
        * porps或者state更新时会触发该函数
        * */
        console.log('组件更新')
    }
    componentWillUnmount(){
        /*
        * 组件将要卸载时调用,一些事件监听和定时器需要在此时清除。
        * */
        console.log('组件删除')
    }
    render(){
        return(
            <div>{this.props.name}{this.state.date}{console.log('组件渲染中')}</div>
        )
    }
}
// Live父组件默认的传值
Live.defaultProps = {
    name: '我的默认props.name'
}
export default Live

上一篇 下一篇

猜你喜欢

热点阅读