• React--纯组件


    1.纯组件说明:

    • 说明:纯组件内部的对比是shallow compare(浅层对比)
    • 对于值类型来说:比较两个值是否相同(直接赋值即可,没有坑)
    • 对于引用类型来说:只好比较对象的引用(地址)是否相同
    • 注意:state或props中属性值为引用类型时,应该创建新数据,不要直接修改原数据
    • 纯组件:PureComponent与React.Componenth功能相似
    • 区别:PureComponent内部自动实现了shouldComponentUpdate钩子,不需要手动比较
    • 原理:纯组件内部通过分别对比前后两次props和state的值,来决定是否更新渲染组件

     

     

    1. import React from 'react';
    2. import ReactDOM from 'react-dom';
    3. // import MyEditor from './components/MyEditor';
    4. class App extends React.PureComponent{
    5. state={
    6. number:0
    7. }
    8. handleClick = () =>{
    9. this.setState(()=>{
    10. return{
    11. number: Math.floor(Math.random()*3)
    12. }
    13. })
    14. }
    15. render(){
    16. console.log('重新渲染')
    17. return(
    18. <div>
    19. <h1>随机数:{this.state.number}h1>
    20. <button onClick={this.handleClick}>重新生成button>
    21. div>
    22. )
    23. }
    24. }

    引用类型的比较:(因为两者的地址一样,无论怎样点击按钮,都不会进行渲染)

    1. class App extends React.PureComponent{
    2. state={
    3. obj:{
    4. number:0
    5. }
    6. }
    7. handleClick = () =>{
    8. //错误演示
    9. const newObj = this.state.obj
    10. newObj.number = Math.floor(Math.random()*3)
    11. this.setState(()=>{
    12. return{
    13. obj:newObj
    14. }
    15. })
    16. }
    17. render(){
    18. console.log('重新渲染')
    19. return(
    20. <div>
    21. <h1>随机数:{this.state.obj.number}h1>
    22. <button onClick={this.handleClick}>重新生成button>
    23. div>
    24. )
    25. }
    26. }

    正确演示:

    1. handleClick = () =>{
    2. //正确演示
    3. const newObj = {...this.state.obj,number:2}
    4. newObj.number = Math.floor(Math.random()*3)
    5. this.setState(()=>{
    6. return{
    7. obj:newObj
    8. }
    9. })
    10. }

     

  • 相关阅读:
    Linux head/tail
    微信小程序:12.页面导航
    MQ 概念介绍 / 配置以及原理 简书
    一言不合就重构
    在北京多有钱能称为富
    总结单例模式的写法
    【期末考试复习】概率论与数理统计(知识点模式 - 复习题1)(内容1)
    笔试强训48天——day14
    芯片工程师求职题目之CPU篇(4)
    Pod 管理与使用
  • 原文地址:https://blog.csdn.net/weixin_53052268/article/details/126154259