如何覆盖反应组件生命周期方法

时间:2017-01-12 10:19:16

标签: reactjs

我想覆盖反应组件生命周期(如 shouldComponentUpdate ),并在必要时调用默认值。我尝试从类似的东西开始:

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

但它不起作用。我错过了什么?

1 个答案:

答案 0 :(得分:1)

我认为最好的方法是编写es7装饰器,你可以这样写一些想法:

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

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

感谢这个装饰器,你可以覆盖react组件中的方法shouldComponentUpdate

用法示例:

@customShouldComponentUpdate
class Foo extends Component{
  //code
}
相关问题