一、创建阶段的生命周期
ps:只有类组件才有生命周期
1、constructor:初始化数据、为事件处理程序绑定 this
2、render:渲染 UI 结构
3、componentDidMount:获取 DOM 元素、发送网络请求
import React from 'react' export default class App extends React.Component { // constructor 是 react 运行阶段遇到的第一个生命周期 // 这个生命周期的作用:初始化数据、为事件处理程序绑定 this constructor() { super() this.state = {} console.warn('constructor首先运行') } // render 是运行阶段执行的第二个生命周期 // 这个生命周期的作用:渲染 UI 结构 render() { console.warn('render 第二个运行') return ( <div></div> ) } // componentDidMount 是创建阶段执行的第三个生命周期 // 这个阶段 DOM 已经完成渲染成功 // 这个生命周期的作用:获取 DOM 元素、发送网络请求 componentDidMount() { console.warn('componentDidMount 第三个运行') } }
二、更新阶段的生命周期
更新阶段触发时机:1、props 值发生了改变
2、this.setState() 更改数据
3、this.forceUpdate() 强制更新组件 (要写在componentDidMount中)
① render:渲染 UI 结构
② componentDidUpdate:发送网络请求以及获取 DOM 元素
import React from 'react' /** * 触发组件更新的时机 * props 值发生了改变 * this.setState() 更改数据 * this.forceUpdate() 强制更新组件 (要写在componentDidMount中) */ export default class App extends React.Component { state = { age: 10 } handle = () => { this.setState({ age: this.state.age + 1 }) } componentDidMount() { } render() { console.warn('我是父组件中的 render') return ( <div> <h4>父组件</h4> <button onClick={this.handle}>更改数据</button> <hr/> <Son age={this.state.age}/> </div> ) } } class Son extends React.Component { // 在更新阶段 首先执行的生命周期是 render // render 的作用也是渲染 UI 结构 // 这个 render 实际上和创建阶段的 render 是同一个 render render() { console.warn('触发了子组件 render') return ( <div> <h4>子组件</h4> <div>{this.props.age}</div> </div> ) } // 在更新阶段,第二个执行的生命周期是 componentDidUpdate // componentDidUpdate的作用是发送网络请求以及获取 DOM 元素 // 在这个阶段,更新的 DOM, 也就是 UI 结构已经渲染完成 componentDidUpdate(prevProps) { console.warn('componentDidUpdate:组件更新完成') // 注意事项: 在componentDidUpdate 这个生命周期中,不能调用 this.setState // 因为容易造成死循环 console.log('上一次数据:',prevProps,'更新后的数据:',this.props) // 如果要调用 this.setState 必须加一个 if 判断条件,也就是说,必须有一个终止的条件 if (prevProps === this.props) { this.setState({ }) } // 为什么不能直接调用 this.setState // 因为 this.setState 会造成数据以及页面更新 // 更新之后,就会造成组件更新,name组件只要一更新,就会调用 componentDidUpdate // 从而又调用 this.setState , 从而造成死循环 } }
三、销毁阶段的生命周期
componentWillUnmount:在组件从页面中卸载,也就是在页面中不在使用该组件的时候
import React from 'react' export default class App extends React.Component { state = { age: 10 } handle = () => { this.setState({ age: this.state.age + 1 }) } componentDidMount() { } render() { // console.warn('我是父组件中的 render') return ( <div> <h4>父组件</h4> <button onClick={this.handle}>更改数据</button> <hr/> { this.state.age === 13 ? <div>不渲染组件</div> : <Son age={this.state.age}/> } </div> ) } } class Son extends React.Component { componentDidMount () { this.timer = setInterval(() => { console.log('定时器正在执行') },500) } render() { // console.warn('触发了子组件 render') return ( <div> <h4>子组件</h4> <div>{this.props.age}</div> </div> ) } // 这是销毁时会执行的生命周期钩子函数 // 作用:在组件从页面中卸载,也就是在页面中不在使用该组件的时候 // 执行相关的清理操作,就是清除当前组件产生的一些冗余数据 componentWillUnmount() { clearInterval(this.timer) } }