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

react之Component存在的2个问题

问题

  • 只要执行setState(),即使不改变状态数据,组件也会重新render()
  • 只当前组件重新render(),就会自动重新render子组件

原因

  • Component中的shouldComponentUpdate()总是返回true

思路

  • 只有当组件的state或props数据发生改变时才重新render()

解决

  • 重写shouldComponentUpdate()方法:比较新旧state或props数据,如果有变化才返回true,如果没有返回false
  • 使用PureComponent:PureComponent重写了shouldComponentUpdate()方法,只有state或props数据有变化才返回true。(只进行state和props数据的浅比较,如果只是数据对象数据变了,返回false)

案例

import React, { PureComponent } from 'react'
import './index.css'export default class Parent extends PureComponent {state = { carName: '奔驰' }changeCar = ()=>{this.setState({carName:'五菱'})}// shouldComponentUpdate(nextProps,nextState){//     console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);//     return !(this.state.carName === nextState.carName)// }render() {console.log('Parent-render');const { carName } = this.statereturn (<div className='parent'><h5>parent组件</h5><span>我的车是:{carName}</span>&nbsp;&nbsp;&nbsp;<button onClick={this.changeCar}>换车</button><Child car='木马'></Child></div>)}
}class Child extends PureComponent {// shouldComponentUpdate(nextProps,nextState){//     console.log('this.state:',this.state,'this.props:',this.props,'nextProps:',nextProps,'nextState:',nextState);//     return !(this.props.car === nextProps.car)// }render() {console.log('Child-render');return (<div className='child'><h5>child组件</h5><div>Child组件从Parent组件拿到的车是:{this.props.car}</div></div>)}
}	

样式文件:

.parent{width: 500px;background-color: aqua;padding: 20px;
}.child{width: 90%;background-color:bisque;padding: 20px;margin-top: 30px;
}

效果实现:
在这里插入图片描述

http://www.lryc.cn/news/224309.html

相关文章:

  • 【论文阅读】Generating Radiology Reports via Memory-driven Transformer (EMNLP 2020)
  • IP协议相关技术
  • Visual Studio2022安装教程【图文详解】(大一小白)编译软件
  • matlab 点云最小二乘拟合平面(PCA法)
  • socks5代理和https代理有什么不同?各自有哪些优点?
  • springboot,spring框架返回204 status code的时候,会吞掉返回值
  • 6-爬虫-scrapy解析数据(使用css选择器解析数据、xpath 解析数据)、 配置文件
  • idea 一直卡在maven正在解析maven依赖
  • 警告:未配置spring boot 配置注解处理器
  • 详解虚拟DOM的原理
  • 开设自己的网站系类03安装数据库(centos版)
  • Flutter StreamBuilder 实现局部刷新 Widget
  • 【代码随想录】算法训练营 第十六天 第六章 二叉树 Part 3
  • 【C++数据结构】顺序存储结构的抽象实现
  • LeetCode75——Day31
  • 小白学爬虫:通过商品ID或商品链接封装接口获取淘宝商品销量数据接口|淘宝商品销量接口|淘宝月销量接口|淘宝总销量接口
  • AI:75-基于生成对抗网络的虚拟现实场景增强
  • 【MySQL数据库】| 索引以及背后的数据结构
  • 家用电脑做服务器,本地服务器搭建,公网IP申请,路由器改桥接模式,拨号上网
  • 原神游戏干货分享:探索璃月的宝箱秘密,提高游戏资源获取效率!
  • idea 2023 设置启动参数、单元测试启动参数
  • RSA加密算法(后端)
  • 挑战100天 AI In LeetCode Day08(热题+面试经典150题)
  • 地铁机电设备健康管理现状及改善方法
  • 安卓NDK开发
  • 高性能网络编程 - 解读5种I/O模型
  • 复盘一个诡异的Bug
  • 【uniapp】通用列表封装组件
  • 17 Linux 中断
  • 微信小程序真机调试连接状态一直在正常和未链接之间反复横跳?