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

时间:2016-03-29 18:08:55

标签: javascript reactjs react-jsx

考虑父组件的两种不同的渲染方法,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指南”的建议处理shouldComponentUpdate

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

在上述两个示例中,子组件始终shallowCompare返回true,即使我传递的对象/子项完全相同(因为引用已更改)。这导致了大量浪费的渲染。

如何在不破坏SCU的情况下将静态对象/子项作为道具传递?

1 个答案:

答案 0 :(得分:0)

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

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

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