学习React系列(一)——React.Component 生命周期

本文详细介绍了React组件从创建、更新到销毁的整个生命周期,并通过一个示例代码展示了各个生命周期方法的执行顺序。对于理解React应用的工作流程及如何优化组件更新非常有帮助。

挂载中(只执行一次)

以下方法在组件实例正被创建和插入到DOM中时调用

constructor()一般用于初始化state和方法的this绑定

componentWillMount()

render()

componentDidMount()  一般用于建立订阅,副作用和ajax获取数据

更新中

属性或者状态的改变会触发更新,以下方法将在组件重绘中被调用

componentWillReceiveProps()  用于处理挂载的组件属性变化引起的状态改变,通过比较来判定是否使用setstate方法。

shouldComponentUpdate()   若返回false则不处罚以下方法,默认返回true

componentWillUpdate()  该方法内部不能调用setstate方法

render()

componentDidUpdate()

移除中

该方法在组件正被移除中被调用

componentWillUnmount()

 

事实胜于雄辩,下面来一段代码,让你了解所有方法的执行顺序,同时里面也包含了不可控组件ref中方法的执行时机

class App extends React.Component{
    constructor(props){
        super(props);
        this.state={
            num:0
        }
        this.changeName = this.changeName.bind(this)
    }
    componentWillMount(){
        console.log('willmount')
    }
    componentDidMount(){
        console.log('didMount')
    }
    componentWillReceiveProps(nextprops){
        console.log('willrecieve')
    }
    shouldComponentUpdate(){
        console.log('shouldupdate')
        return true
    }
    componentWillUpdate(){
        console.log('willupdate')
    }
    componentDidUpdate(){
        console.log('didiupdate')
    }
    componentWillUnmount(){
        console.log('unmount')
    }
    changeName(){
        let num = this.state.num+1
        this.setState({
            num
        })
    }
    render(){
        console.log('render')
        return(
            <div onClick={this.changeName} ref={div=>{console.log(div)}}>
                {this.state.num}
            </div>
        )
    }
}

 

文中没有提到使用场景的方法不推荐使用,因为基本所有的操作都可以被说明用途的替代掉,当然抛出一定状态下,eg:更新完成之后我要alert一下,如果存在什么问题可以留言,我会及时回复

参考:https://reactjs.org/docs/react-component.html#constructor

转载于:https://www.cnblogs.com/zale-blogs/p/8463596.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值