当前位置: 首页 > article >正文

React - 组件优化、children props 与 render props、错误边界

一、组件优化1、问题引入1基本介绍只要执行 setState即使不改变状态数据, 组件也会重新 render只要当前组件重新 render就会自动重新 render 子组件纵使子组件没有用到父组件的任何数据只要父组件更新不管子组件的 props 变没变子组件都会重新渲染2演示import { Component } from react; import Child from ../Child; import ./index.css; export class Parent extends Component { state { username: tom, age: 18 }; change () { this.setState({ username: this.state.username, age: this.state.age }); }; render() { console.log(Parent 渲染了); const { username, age } this.state; return ( div classNameparent h3Parent/h3 divusername: {username}/div divage: {age}/div button onClick{this.change}点我修改/button Child / /div ); } }.parent{width:500px;background-color:orange;padding:8px;}import { Component } from react; import ./index.css; export default class Child extends Component { render() { console.log(Child 渲染了); return ( div classNamechild h3Child/h3 /div ); } }.child{width:100%;background-color:skyblue;padding:8px;}首次渲染输出结果如下Parent 渲染了 Child 渲染了第 1 次点击【点我修改】按钮输出结果如下Parent 渲染了 Child 渲染了第 2 次点击【点我修改】按钮输出结果如下Parent 渲染了 Child 渲染了2、问题原因Component 中的 shouldComponentUpdate 方法总是返回 true3、处理策略重写 shouldComponentUpdate 方法比较新旧 state 或 props 数据如果有变化则返回 true没有则返回 falseimport { Component } from react; import Child from ../Child; import ./index.css; export class Parent extends Component { state { username: tom, age: 18 }; change () { this.setState({ username: this.state.username }); }; shouldComponentUpdate(nextProps, nextState) { // nextProps 是接下来要变化的目标 props // nextState 是接下来要变化的目标 state return nextState.username ! this.state.username || nextState.age ! this.state.age; } render() { console.log(Parent 渲染了); const { username, age } this.state; return ( div classNameparent h3Parent/h3 divusername: {username}/div divage: {age}/div button onClick{this.change}点我修改/button Child / /div ); } }使用 PureComponent它重写了 shouldComponentUpdate 方法只有 state 或 props 数据有变化才返回 trueimport { PureComponent } from react; import Child from ../Child; import ./index.css; export class Parent extends PureComponent { state { username: tom, age: 18 }; change () { this.setState({ username: this.state.username }); }; render() { console.log(Parent 渲染了); const { username, age } this.state; return ( div classNameparent h3Parent/h3 divusername: {username}/div divage: {age}/div button onClick{this.change}点我修改/button Child / /div ); } }4、注意事项1基本介绍PureComponent 只是进行 state 和 props 数据的浅比较如果是数据对象内部数据变了返回 false不要直接修改 state 数据而是要产生新数据2演示import { PureComponent } from react; import Child from ../Child; import ./index.css; export class Parent extends PureComponent { state { person: { username: tom, age: 18, }, }; // 这里改变了第 1 层 change1 () { this.setState({ person: { ...this.state.person } }); }; // 这里改变了第 2 层没有改变第 1 层 change2 () { const { person } this.state; person.username jerry; person.age 20; this.setState({ person: person }); }; render() { console.log(Parent 渲染了); const { username, age } this.state.person; return ( div classNameparent h3Parent/h3 divusername: {username}/div divage: {age}/div button onClick{this.change1}点我修改 1/button button onClick{this.change2}点我修改 2/button Child / /div ); } }.parent{width:500px;background-color:orange;padding:8px;}import { Component } from react; import ./index.css; export default class Child extends Component { render() { console.log(Child 渲染了); return ( div classNamechild h3Child/h3 /div ); } }.child{width:100%;background-color:skyblue;padding:8px;}首次渲染输出结果如下Parent 渲染了 Child 渲染了第 1 次点击【点我修改 1】按钮输出结果如下Parent 渲染了 Child 渲染了第 2 次点击【点我修改 2】按钮输出结果如下Parent 渲染了 Child 渲染了第 1 次点击【点我修改 2】按钮输出结果如下无第 2 次点击【点我修改 2】按钮输出结果如下无二、children props 与 render props1、基本介绍children props 是通过组件标签体的方式向组件内部传递内容在组件内部可以通过props.children来获取这些内容但是如果内容需要父组件内部的数据children props 做不到需要使用 render props 来实现2、演示1children propsexport default function Card(props) { return ( h3Card/h3 {props.children} / ); }import Card from ./components/Card; export default function App() { return ( Card p这是卡片内部的内容/p button点击按钮/button /Card / ); }2render propsimport { useState } from react; export default function Card(props) { const [content] useState(这是一段测试内容); return ( h3Card/h3 {props.render(content)} / ); }export default function CardInner(props) { return ( p这是卡片内部的内容/p button点击按钮/button div{props.content}/div / ); }import Card from ./components/Card; import CardInner from ./components/CardInner; export default function App() { return ( Card render{(content) CardInner content{content} /} / / ); }三、错误边界1、基本介绍错误边界Error Boundary用来捕获后代组件错误渲染出备用页面只能捕获后代组件生命周期产生的错误不能捕获自己组件产生的错误以及其他组件在合成事件、定时器中产生的错误2、演示import { PureComponent } from react; import Child from ../Child; import ./index.css; export class Parent extends PureComponent { state { hasError: , }; static getDerivedStateFromError(error) { console.log(, error); return { hasError: error }; } componentDidCatch(error, info) { console.log(此处统计错误反馈给服务); console.log(error, info); } render() { return ( div classNameparent h3Parent/h3 {this.state.hasError ? h3当前网络不稳定稍后再试/h3 : Child /} /div ); } }.parent{width:500px;background-color:orange;padding:8px;}import { Component } from react; import ./index.css; export default class Child extends Component { // state { // users: [ // { id: 001, name: tom, age: 18 }, // { id: 002, name: jack, age: 19 }, // { id: 003, name: merry, age: 20 }, // ], // }; // 模拟一个错误 state { users: test, }; render() { return ( div classNamechild h3Child/h3 {this.state.users.map((userObj) { return ( div key{userObj.id} {userObj.name} ----- {userObj.age} /div ); })} /div ); } }.child{width:100%;background-color:skyblue;padding:8px;}

相关文章:

React - 组件优化、children props 与 render props、错误边界

一、组件优化 1、问题引入 (1)基本介绍只要执行 setState,即使不改变状态数据, 组件也会重新 render只要当前组件重新 render,就会自动重新 render 子组件,纵使子组件没有用到父组件的任何数据只要父组件更新&#xff…...

OpenSSF Scorecard安全策略检查:保护代码仓库的终极完整指南

OpenSSF Scorecard安全策略检查:保护代码仓库的终极完整指南 【免费下载链接】scorecard OpenSSF Scorecard - Security health metrics for Open Source 项目地址: https://gitcode.com/gh_mirrors/sc/scorecard OpenSSF Scorecard是一款由Open Source Secu…...

终极MFE-starter缓存策略指南:Service Worker与浏览器缓存优化全解析

终极MFE-starter缓存策略指南:Service Worker与浏览器缓存优化全解析 【免费下载链接】MFE-starter MFE Starter 项目地址: https://gitcode.com/gh_mirrors/mf/MFE-starter MFE-starter作为现代前端微服务架构的开发利器,其缓存策略直接影响应用…...

告别复制粘贴!PDF-Parser-1.0实战:3步提取论文/报告/合同所有内容

告别复制粘贴!PDF-Parser-1.0实战:3步提取论文/报告/合同所有内容 1. 为什么你需要PDF-Parser-1.0? 还在为PDF文档中的内容提取而烦恼吗?无论是学术论文中的复杂公式,财务报告里的精密表格,还是法律合同中…...

终极DevSecOps安全测试工具大全:OWASP ZAP、Brakeman等实战应用指南

终极DevSecOps安全测试工具大全:OWASP ZAP、Brakeman等实战应用指南 【免费下载链接】awesome-devsecops An authoritative list of awesome devsecops tools with the help from community experiments and contributions. 项目地址: https://gitcode.com/gh_mir…...

BAAI/bge-m3环境配置全攻略:WebUI集成与语义分析服务搭建

BAAI/bge-m3环境配置全攻略:WebUI集成与语义分析服务搭建 1. 环境准备与快速部署 1.1 系统要求与依赖安装 BAAI/bge-m3作为当前最强大的开源语义嵌入模型之一,对运行环境有特定要求。以下是推荐的配置方案: 操作系统:Linux (U…...

使用Knockout.js构建完全键盘友好的无障碍导航菜单:终极指南

使用Knockout.js构建完全键盘友好的无障碍导航菜单:终极指南 【免费下载链接】knockout Knockout makes it easier to create rich, responsive UIs with JavaScript 项目地址: https://gitcode.com/gh_mirrors/kn/knockout 在现代Web开发中,创建…...

Rack错误处理终极指南:ShowExceptions中间件详解与实战技巧

Rack错误处理终极指南:ShowExceptions中间件详解与实战技巧 【免费下载链接】rack A modular Ruby web server interface. 项目地址: https://gitcode.com/gh_mirrors/ra/rack Rack是Ruby生态系统中最核心的Web服务器接口,为Ruby开发者提供了模块…...

防撤回解决方案:系统级保护的即时通讯消息安全增强

防撤回解决方案:系统级保护的即时通讯消息安全增强 【免费下载链接】RevokeMsgPatcher :trollface: A hex editor for WeChat/QQ/TIM - PC版微信/QQ/TIM防撤回补丁(我已经看到了,撤回也没用了) 项目地址: https://gitcode.com/G…...

Spring Authorization Server 安全审计和合规性检查终极指南:10个关键实践

Spring Authorization Server 安全审计和合规性检查终极指南:10个关键实践 【免费下载链接】spring-authorization-server Spring Authorization Server 项目地址: https://gitcode.com/gh_mirrors/sp/spring-authorization-server Spring Authorization Ser…...

终极指南:5分钟掌握Fan Control风扇控制软件,彻底优化电脑散热与噪音

终极指南:5分钟掌握Fan Control风扇控制软件,彻底优化电脑散热与噪音 【免费下载链接】FanControl.Releases This is the release repository for Fan Control, a highly customizable fan controlling software for Windows. 项目地址: https://gitco…...

Alex.js 终极指南:如何用智能工具提升写作包容性

Alex.js 终极指南:如何用智能工具提升写作包容性 【免费下载链接】alex Catch insensitive, inconsiderate writing 项目地址: https://gitcode.com/gh_mirrors/al/alex Alex.js 是一款强大的开源工具,专为检测和改进写作中的不敏感、不周到表达而…...

如何构建现代化单页应用导航系统:从基础原理到实战实现

如何构建现代化单页应用导航系统:从基础原理到实战实现 【免费下载链接】screencasts Code that goes along with my screencasts. 项目地址: https://gitcode.com/gh_mirrors/sc/screencasts 单页应用(SPA)导航是现代Web开发的核心技…...

mPLUG视觉问答快速上手:5分钟完成本地部署,支持多格式图片+自然语言提问

mPLUG视觉问答快速上手:5分钟完成本地部署,支持多格式图片自然语言提问 你是不是经常遇到这种情况:看到一张复杂的图表,想快速知道它表达了什么;或者拿到一张产品设计图,想了解其中的细节信息;…...

如何让你的Windows电脑重获新生?系统优化与个性化全攻略

如何让你的Windows电脑重获新生?系统优化与个性化全攻略 【免费下载链接】Winhance-zh_CN A Chinese version of Winhance. C# application designed to optimize and customize your Windows experience. 项目地址: https://gitcode.com/gh_mirrors/wi/Winhance-…...

OpenClaw定时任务管理:千问3.5-27B实现凌晨自动备份

OpenClaw定时任务管理:千问3.5-27B实现凌晨自动备份 1. 为什么需要AI驱动的定时任务? 上个月我经历了一次惨痛的数据丢失——连续三天熬夜写的代码,因为笔记本突然蓝屏而全部消失。虽然最终通过碎片文件恢复了部分内容,但这件事…...

7-Zip ZS高效压缩算法深度解析:多格式压缩实战配置指南

7-Zip ZS高效压缩算法深度解析:多格式压缩实战配置指南 【免费下载链接】7-Zip-zstd 7-Zip with support for Brotli, Fast-LZMA2, Lizard, LZ4, LZ5 and Zstandard 项目地址: https://gitcode.com/gh_mirrors/7z/7-Zip-zstd 7-Zip ZS(7-Zip-zstd…...

GPUStack 在华为昇腾 I A 服务器上的保姆级部署指南几

开发个什么Skill呢? 通过 Skill,我们可以将某些能力进行模块化封装,从而实现特定的工作流编排、专家领域知识沉淀以及各类工具的集成。 这里我打算来一次“套娃式”的实践:创建一个用于自动生成 Skill 的 Skill,一是用…...

Sparrow App快速上手:5分钟学会API测试和调试

Sparrow App快速上手:5分钟学会API测试和调试 【免费下载链接】sparrow-app Your next-gen API testing and development tool. 项目地址: https://gitcode.com/gh_mirrors/sp/sparrow-app Sparrow App是一款下一代API测试和开发工具,能帮助开发者…...

微信聊天记录备份:数字时代的数据主权与记忆守护之道

微信聊天记录备份:数字时代的数据主权与记忆守护之道 【免费下载链接】WeChatMsg 提取微信聊天记录,将其导出成HTML、Word、CSV文档永久保存,对聊天记录进行分析生成年度聊天报告 项目地址: https://gitcode.com/GitHub_Trending/we/WeChat…...

DeepTutor智能复习系统:基于遗忘曲线的高效复习策略终极指南

DeepTutor智能复习系统:基于遗忘曲线的高效复习策略终极指南 【免费下载链接】DeepTutor "DeepTutor: Agent-Native Personalized Learning Assistant" 项目地址: https://gitcode.com/GitHub_Trending/dee/DeepTutor DeepTutor是一个基于AI智能体…...

从xcode-install到xcodes:项目迁移指南与版本管理工具演进

从xcode-install到xcodes:项目迁移指南与版本管理工具演进 【免费下载链接】xcode-install 🔽 Install and update your Xcodes 项目地址: https://gitcode.com/gh_mirrors/xc/xcode-install xcode-install是一款曾广受欢迎的Xcode版本管理工具&a…...

突破学术资源壁垒:Unpaywall扩展全方位应用指南

突破学术资源壁垒:Unpaywall扩展全方位应用指南 【免费下载链接】unpaywall-extension Firefox/Chrome extension that gives you a link to a free PDF when you view scholarly articles 项目地址: https://gitcode.com/gh_mirrors/un/unpaywall-extension …...

Cursor Free VIP开源工具:Cursor功能扩展完整技术指南

Cursor Free VIP开源工具:Cursor功能扩展完整技术指南 【免费下载链接】cursor-free-vip [Support 0.45](Multi Language 多语言)自动注册 Cursor Ai ,自动重置机器ID , 免费升级使用Pro 功能: Youve reached your tri…...

Databricks推出AiChemy多智能体AI系统,助力药物研发加速

Databricks近日发布了一套名为AiChemy的多智能体AI参考架构,该系统通过模型上下文协议(MCP)将其平台上的企业内部数据与外部科学数据库相结合,旨在加速药物研发过程中的靶点识别与候选化合物评估等关键任务。靶点识别与候选化合物…...

AWS首席执行官解释为何同时投资Anthropic与OpenAI并不存在冲突

AWS首席执行官马特加曼表示,亚马逊近期对OpenAI完成了500亿美元的投资,此前已与Anthropic建立长期合作关系并累计投入80亿美元。他认为,对于这家云计算巨头而言,处理此类利益冲突早已是家常便饭。加曼在本周于旧金山举办的HumanX大…...

高并发系统线程爆炸危机迫在眉睫,Java 25虚拟线程已是唯一解?阿里/Netflix/Stripe真实迁移时间表首度公开

第一章:Java 25虚拟线程:高并发架构演进的分水岭Java 25正式将虚拟线程(Virtual Threads)从预览特性转为标准特性,标志着JVM在轻量级并发模型上的根本性突破。虚拟线程并非简单的API升级,而是JVM调度层与操…...

PHP异步I/O迁移紧急预案(含同步代码自动转换工具链+CI/CD熔断检测脚本)

第一章:PHP异步I/O迁移紧急预案概览当传统阻塞式 PHP 应用遭遇高并发 I/O 瓶颈(如大量 HTTP 请求、数据库查询或文件读写),服务响应延迟激增、连接池耗尽、CPU 利用率反常偏低——此时,异步 I/O 迁移已非优化选项&…...

CV-CUDA快速入门:10分钟学会构建你的第一个GPU加速图像处理应用

CV-CUDA快速入门:10分钟学会构建你的第一个GPU加速图像处理应用 【免费下载链接】CV-CUDA CV-CUDA™ is an open-source, GPU accelerated library for cloud-scale image processing and computer vision. 项目地址: https://gitcode.com/gh_mirrors/cv/CV-CUDA …...

一款基于.NET开源的B站视频下载工具,简单高效,开箱即用

🌈前言作为程序员,相信大家都经常在B站刷学习视频、技术教程,有时候遇到优质内容,想下载下来离线观看、反复琢磨,却找不到好用的工具——要么广告多,要么功能不全,要么操作复杂🔖介绍…...