加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

实现React中PureComponent的浅比较

发布时间:2020-12-15 09:30:09 所属栏目:百科 来源:网络整理
导读:React.Purecomponent与React.Component几乎完全相同,但React.PureComponent通过prop和state的浅比较来实现shouldComponentUpdate() React.PureComponent 的shouldComponentUpdate()只会对对象进行浅比较。如果对象包含复杂的数据结构,它可能会因深层的数据

React.Purecomponent与React.Component几乎完全相同,但React.PureComponent通过prop和state的浅比较来实现shouldComponentUpdate()

React.PureComponent 的shouldComponentUpdate()只会对对象进行浅比较。如果对象包含复杂的数据结构,它可能会因深层的数据不一致
而产生错误的否定判断(表现为对象身侧你的数据已改变视图却没有更新)

那么React.PureComponent的浅比较是如何实现的呢?

让我们来重写React.Component的shouldComponentUpdate()方法:

在该方法中定义一个函数shallowEquals,该函数接收两个参数

shoudComponentUpdate(nextProps,nextState){
    function shallowEquals(oldValue,newValue){
    //Object.is() 判断两个值是否相同
    //如果两个值都是对象类型,指向同一个对象才返回ture
    if(Object.is(oldValue,newValue)){
      return true
    }

    //这里知道传入的参数为对象就不做判断了

    const oldKeys = Object.keys(oldValue),newKeys = Object.keys(newValue)
    
    if(oldKeys.length !== newKeys.length ) return false

    for(let i = 0;i < oldKeys.length;i++){
      //通过Object.is判断这两个属性值是否相同
      //即使两个对象属性与属性值完全相同,但是不是同一个引用
      //也会返回false
      let result = newValue.hasOwnProperty(oldKeys[i]) && Object.is(oldValue[oldKeys[i]],newValue[oldKeys[i]])
      if(!result) return false
    }

    return true
  }

  return shallowEquals(this.props,nextProps) && shallowEquals(this.state,nextState)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读