
React 学习笔记 —— 组件生命周期(包含17新版和旧版对比)
发布日期:2021-05-12 21:18:31
浏览次数:19
分类:精选文章
本文共 3955 字,大约阅读时间需要 13 分钟。
生命周期优化是React开发中一个核心的概念,理解它能帮助开发者更好地管理组件的状态和渲染流程。本文将深入探讨React组件的生命周期,并结合实际案例,阐述如何在不同场景下优化组件的更新和卸载流程。
React 组件生命周期概述
React 组件生命周期可以分为三个主要阶段:
1. 初始化阶段
初始化阶段从ReactDOM.render()
触发,通常由componentDidMount
标记。该阶段包括以下关键步骤:
constructor()
: 在组件实例化时执行,通常用于初始化初始状态。componentWillMount()
: 组件将要挂载时执行,适用于初始化数据或设置定时器。render()
: 首次渲染或更新渲染时调用,负责将组件转换为最初的 JSX 结构。componentDidMount()
: 组件挂载完成时执行,通常用于发送网络请求或设置 DOM 事件监听。
2. 更新阶段
更新阶段由组件内部的this.setState()
或父组件的render()
重新渲染触发,主要流程包括:
shouldComponentUpdate()
: 检查是否需要更新,返回false
可跳过渲染。componentWillUpdate()
: 组件将要更新时执行,适用于权限检查或数据处理。render()
: 渲染过程,类似于初始化阶段。componentDidUpdate()
: 组件更新完成时执行,可用于状态恢复或 DOM 更新。
3. 卸载阶段
卸载阶段由ReactDOM.unmountComponentAtNode()
触发,主要步骤包括:
componentWillUnmount()
: 组件将要卸载时执行,常用于清理定时器或释放资源。
React 组件生命周期优化实例
以下是几个基于生命周期优化的常见场景:
####_SCENE 1: 首次渲染优化
在初始化阶段,开发者应尽量减少render()
方法中逻辑的复杂度,避免在初始渲染和更新阶段重复执行时间敏感的操作。例如: class Demo extends React.Component { constructor() { super(); this.state = { count: 0 }; console.log('constructor'); } componentWillMount() { console.log('componentWillMount'); } render() { console.log('render'); return (); } componentDidMount() { console.log('componentDidMount'); }}{this.state.count}
####_SCENE 2: 状态更新优化
在更新阶段,为了避免不必要的渲染,建议在shouldComponentUpdate()
中进行增量性检查。如: class Demo extends React.Component { constructor() { super(); this.state = { count: 0 }; console.log('constructor'); } shouldComponentUpdate() { console.log('shouldComponentUpdate'); return true; } // 其他回调函数保持不变}
####_SCENE 3: 强制更新
在某些情况下,开发者需要强制触发更新而不经setState
。可以借助forceUpdate()
方法: class Demo extends React.Component { constructor() { super(); this.state = { count: 0 }; console.log('constructor'); } render() { console.log('render'); return (); }}{this.state.count}
####parent组件和子组件的交互
React 17 版本更新
React 17 版本对生命周期模型进行了重要调整:
####废弃的钩子函数
React
公告称三个钩子将被废弃: componentWillReceiveProps
componentWillMount
componentWillUpdate
替代方案:
- 使用新的
UNSAFE_
前缀命名:UNSAFE_componentWillReceiveProps
UNSAFE_componentWillMount
UNSAFE_componentWillUpdate
新增钩子函数
React 17 引入了两个新的钩子:
getDerivedStateFromProps
: 从props
中获取派生的状态。getSnapshotBeforeUpdate
: 在更新前获取快照。
new钩子函数示例
class Demo extends React.Component { static getDerivedStateFromProps(props, state) { console.log('getDerivedStateFromProps'); return null; } render() { console.log('render'); return ({this.props.count}); } // 其他回调函数保持不变}
getSnapshotBeforeUpdate 示例
以下是一个使用 getSnapshotBeforeUpdate
的简单示例:
import React from 'react';class NewsList extends React.Component { state = { newsArr: [] }; ref = React.createRef(); componentDidMount() { setInterval(() => { const news = `新闻${this.state.newsArr.length + 1}`; this.setState({ newsArr: [news, ...this.state.newsArr] }); }, 1000); console.log('componentDidMount'); } getSnapshotBeforeUpdate(prevProps, prevState) { return this.ref.current.scrollHeight; } componentDidUpdate(prevProps, prevPk, prevPstate, snapshot) { console.log('componentDidUpdate'); this.ref.current.scrollTop += this.ref.current.scrollHeight - snapshot; } render() { return ({this.state.newsArr.map((n, index) => (); }}{n}))}
总结
通过上述分析,可以看出 React 组件的生命周期优化对提升应用性能和开发体验至关重要。在实际开发中,应根据项目需求合理选择生命周期钩子,并采用合适的优化策略,以确保组件的高效运行和良好的用户体验。
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2025年04月07日 12时05分36秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
【换行符】什么时候用cin.get()吃掉输入流中的换行符
2019-03-09
【二叉树】已知后序与中序求先序
2019-03-09
数组范围的动态扩容
2019-03-09
解决Nginx 404 not found问题
2019-03-09
计算机网络之第三章笔记--数据链路层
2019-03-09
创建型模式之简单工厂模式实例及代码操作
2019-03-09
广东外语外贸大学第三届网络安全大赛Writeup
2019-03-09
跟着燕青学分布式事务控制技术方案
2019-03-09
Activiti视频分享
2019-03-09
VS2019 报错: LINK Error 无法找到 MSCOREE.lib的解决办法
2019-03-09
关于JS中的内存溢出与内存泄漏
2019-03-09
算法训练——字符串合并
2019-03-09
2021-04-23
2019-03-09
Linux编程基础之创建两个子进程而不创建孙子进程
2019-03-09
hadoop 分布式文件系统的计算和高可用
2019-03-09
【Linux】VMware Workstation 不可恢复错误: (vcpu-0)
2019-03-09
VS中 fatal error LNK1123: 转换到 COFF 期间失败 的解决方法
2019-03-09
关于Img标签在固定宽高的容器内部以图片比例缩放存在
2019-03-09
pyhton---异常处理的终极语法、网页访问基本读取、网页访问异常处理
2019-03-09
ant design pro v5去掉右边content区域的水印
2019-03-09