简体   繁体   中英

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

Consider the two different render method of Parent Component, P :

Example 1

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

Example 2

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

In ChildComponent

Child component handles shouldComponentUpdate as recommended by React Guide.

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

In both the above expample cases shallowCompare of child component always returns true, even if the object / child I'm passing is exactly the same (because the references changed). This is causing a lot of wasted renders.

How does one pass a static object / child as props without breaking SCU?

Maybe switching to an immutable data structure would help since then the SCU hook will only need to compare reference inequalities:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM