【React -- 4/100】 生命周期

生命周期

概述

意义:组件的生命周期有助于理解组件的运行方式,完成更复杂的组件功能、分析组件错误原因等

组件的生命周期: 组件从被创建到挂载到页面中运行,再到组件不在时卸载的过程

生命周期的每个阶段总是伴随着一些方法调用,这些方法就是生命周期的钩子函数

构造函数的作用:为开发人员在不同阶段操作组件提供了实际

组件生命周期的三个阶段

1 - 创建时(挂载阶段)
	执行时机: 组件创建时(页面加载时)
    执行顺序: constructor() --> render() --> componentDidMount()

生命周期钩子函数:
constructor()
	初始化state
    为事件处理程序绑定this
render()
	渲染UI
componentDidMount() 
	进行DOM操作
    发送ajax请求

2、 运行阶段
触发组件更新的三种情况

执行条件:
	1、setState()
	2、forceUpdata()
	3、组件接收到新的props
	
render() --> componentDidMount()

组件更新

componentDidUpdate()
    拿到上一次的props  -- : prevProps
    拿到这一次的props  -- : this.props

3、卸载阶段

钩子函数:
	componentWillUnmount
		执行清理工作,防止内存泄漏



getDerivedStateFromProps()`

- getDerivedStateFromProps 会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容
- 不管原因是什么,都会在每次渲染前触发此方法

shouldComponentUpdate()

- 根据 shouldComponentUpdate() 的返回值,判断 React 组件的输出是否受当前 state 或 props 更改的影响。默认行为是 state 每次发生变化组件都会重新渲染
- 当 props 或 state 发生变化时,shouldComponentUpdate() 会在渲染执行之前被调用。返回值默认为 true

getSnapshotBeforeUpdate()

- getSnapshotBeforeUpdate() 在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期的任何返回值将作为参数传递给 componentDidUpdate()
- 此用法并不常见,但它可能出现在 UI 处理中,如需要以特殊方式处理滚动位置的聊天线程等
class Parent extends React.Component {
    constructor() {
        console.log( ' constructor ');
        super();
        this.state = {
            count: 0
        }
    }
    handleClick = () => {
        this.setState({
            count: this.state.count + 1
        })
    };

    componentDidMount() {
        console.log('componentDidMount');
    }

    render() {
        console.log( ' render ')
        return (
            <div>
                {/!* 调用子组件, 传递参数给子组件*!/}
                {
                    this.state.count >= 3 ?
                        <p>over</p> :
                        <Child count={this.state.count} />
                }
                <button onClick={this.handleClick}>click + 1</button>
            </div>
        )
    }
}

class Child extends React.Component {
    componentDidMount() {
        // 设置定时器
        this.timerID = setInterval(() => {
            console.log('定时炸弹开始')
        }, 500)
    }

    componentWillUnmount() {
        console.log('卸载组件钩子函数');
        // 清除定时器  不清理会造成内存泄漏
        clearInterval(this.timerID)
    }
    render() {
        console.log( 'child render 钩子函数')
        return (
            <div>
                <p>count: {this.props.count}</p>
            </div>
        )
    }
}

ReactDOM.render(<Parent/>, document.getElementById('root'))
posted @ 2019-12-05 19:55  CNYangx  阅读(155)  评论(0编辑  收藏  举报