簡體   English   中英

如何覆蓋React組件生命周期方法

[英]How to override react component lifecycle methods

我想重寫react組件的生命周期(例如shouldComponentUpdate ),並在必要時調用默認的生命周期。 我嘗試從類似以下內容開始:

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

但這行不通。 我想念什么?

我認為最好的方法是編寫es7裝飾器,您可以這樣寫:

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

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

感謝這個裝飾器,您可以在react component中重寫方法shouldComponentUpdate

用法示例:

@customShouldComponentUpdate
class Foo extends Component{
  //code
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM