react——生命周期函数

生命周期函数指在某一时刻组件会自动调用执行的函数

生命周期函数

// 组件挂载时
componentWillMount // 组件被挂载页面前自动执行
render // 组件挂载
componentDidMount // 组件被挂载页面后自动执行

// 数据更新时
componentWillReceiveProps // 一个组件从父组件接受 props 参数,且父组件 render 函数重新被执行时自动执行
shouldComponentUpdate // 组件即将被变更时执行(必须返回一个布尔值,告诉组件是否需要被更新)
componentWillUpdate // 在 shouldComponentUpdate 返回 true 后,且页面还未更新挂载时会被执行
render // 组件更新挂载
componentDidUpdate // 组件更新挂载后执行

// 组件销毁时
componentWillUnmount // 组件被销毁时执行
初始化

setup props and state

Mounting(挂载)
Created with Raphaël 2.2.0 componentWillMount render componentDidMount
    // 组件被挂载页面前自动执行
    componentWillMount() {}

    // 组件挂载
    render() {
        return <div></div>
    }

    // 组件被挂载页面后自动执行
    componentDidMount() {}
Updation
  • props
Created with Raphaël 2.2.0 componentWillReceiveProps shouldComponentUpdate(true 则继续,false 停止) componentWillUpdate render componentDidUpdate
  • state
Created with Raphaël 2.2.0 shouldComponentUpdate(true 则继续,false 停止) componentWillUpdate render componentDidUpdate
    // 一个组件从父组件接受 props 参数,且父组件 render 函数重新被执行时自动执行
    componentWillReceiveProps() {}
    
    // 组件即将被变更时执行(必须返回一个布尔值,告诉组件是否需要被更新)
    shouldComponentUpdate() {
        // 如果返回 false,页面就不被更新了
        return true
    }

    // 在 shouldComponentUpdate 返回 true 后,且页面还未更新挂载时会被执行
    componentWillUpdate() {}

    // 组件更新挂载
    render() {
        return <div></div>
    }

    // 组件更新挂载后执行
    componentDidUpdate(){}
Unmounting
    // 组件被销毁时执行
    componentWillUnmount() {}

生命周期使用

  • componentDidMount:数据请求执行阶段
  • shouldComponentUpdate:优化性能
    // 避免父组件改变导致每次子组件重新渲染带来的性能问题
    // next 指代接下来变化后的 props 或 state 状态
    shouldComponentUpdate(nextProps, nextState) {
        return nextProps.item !== this.props.item
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值