如何在不破坏shouldComponentUpdate的情况下传递对象/子对象作为道具

How does one pass objects / children as props without breaking shouldComponentUpdate?

本文关键字:对象 情况下 shouldComponentUpdate      更新时间:2023-09-27

考虑两种不同的父组件渲染方法p:

示例1

render() {
  return 
  <ChildComponent propA={ { staticKey: staticValue} }/>
}

示例2

render() {
  return someStaticData.map( data => 
    <ChildComponent>
      <span> 
      {
       data.value.map(dataInner => 
         <span>
           { dataInner.value } 
         <span>
      )} 
     </span>
    </ChildComponent>
  )
}

在ChildComponent中

子组件按照React Guide的建议处理shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState) {
  return shallowCompare(this, nextProps, nextState);
}

在上述两种示例情况下,子组件shallowCompare总是返回true,即使我传递的对象/子对象完全相同(因为引用发生了更改)。这导致了大量渲染的浪费。

如何在不破坏SCU的情况下将静态物体/儿童作为道具传递?

也许切换到不可变的数据结构会有所帮助,因为从那时起,SCU钩子只需要比较引用不等式:

http://facebook.github.io/immutable-js/

https://github.com/rtfeldman/seamless-immutable

相关文章: