0

I would like to override react component lifecycles (like shouldComponentUpdate) and call the default ones if necessary. I tried starting with something like:

shouldComponentUpdate(nextProps, nextState) {
    return super.shouldComponentUpdate(nextProps, nextState);
}

But it does not work. What am I missing?

dwjohnston
  • 11,163
  • 32
  • 99
  • 194
masciugo
  • 1,113
  • 11
  • 19
  • How are you transpiling your code? This works for me when I use babel with the correct es6 transforms + polyfill. Also read this: http://stackoverflow.com/questions/32615034/call-parent-function-which-is-being-overridden-by-child-during-constructor-chain – Sergiu Paraschiv Jan 12 '17 at 11:12
  • as docs say https://facebook.github.io/react/docs/react-component.html#overview React.Component is an abstract class so there is no default implementation available. You need to define it in your components. – iurii Jan 12 '17 at 13:41

1 Answers1

2

I think the best way is write es7 decorator, you can write somethink like this:

function shouldComponentUpdate(nextProps, nextState) {
  //your custom shouldComponentUpdate function
}

function customShouldComponentUpdate(component) {
  component.prototype.shouldComponentUpdate = shouldComponentUpdate;
  return component;
}

Thanks this decorator you can override method shouldComponentUpdate in react component.

usage example:

@customShouldComponentUpdate
class Foo extends Component{
  //code
}
Piotr Białek
  • 2,569
  • 1
  • 17
  • 26