2017-06-13 24 views
3

我知道shouldComponentUpdate以及PureComponent的功能。但我想知道如果我可以一起使用這兩者嗎?我可以在PureComponent中使用shouldComponentUpdate

說我有很多道具,我想讓PureComponent內的淺比較手柄。除了1道,需要巧妙比較一下。那麼是否可以使用shouldComponentUpdate呢? React會考慮哪個結果?

換句話說,React會調用PureComponent的淺對比然後打電話給我shouldComponentUpdate?或我的shouldComponentUpdate會覆蓋原來的?

這將是很好,如果它的雙層,如果PureComponent返回false,控制進入我的shouldComponentUpdate,我有另一個機會return false

回答

4

你要首先在開發環境中得到一個警告爲React source code檢查,看是否該方法被定義或沒有時處理一個PureComponent

if (
    isPureComponent(Component) && 
    typeof inst.shouldComponentUpdate !== 'undefined' 
) { 
    warning(
    false, 
    '%s has a method called shouldComponentUpdate(). ' + 
     'shouldComponentUpdate should not be used when extending React.PureComponent. ' + 
     'Please extend React.Component if shouldComponentUpdate is used.', 
    this.getName() || 'A pure component', 
); 
} 

然後,渲染時,如果這種方法被定義,它實際上會skip 甚至沒有檢查組件一個PureComponent並使用您自己的實現。所以

if (inst.shouldComponentUpdate) { 
    if (__DEV__) { 
    shouldUpdate = measureLifeCyclePerf(
    () => inst.shouldComponentUpdate(nextProps, nextState, nextContext), 
     this._debugID, 
     'shouldComponentUpdate', 
    ); 
    } else { 
    shouldUpdate = inst.shouldComponentUpdate(
     nextProps, 
     nextState, 
     nextContext, 
    ); 
    } 
} else { 
    if (this._compositeType === ReactCompositeComponentTypes.PureClass) { 
    shouldUpdate = 
     !shallowEqual(prevProps, nextProps) || 
     !shallowEqual(inst.state, nextState); 
    } 
} 

通過實現自己的shouldComponentUpdatePureComponent,你就失去了淺層比較。

0

根據DOC:https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate

如果您確定特定成分是分析後慢,你可以改變它從React.PureComponent與淺propstate比較實現shouldComponentUpdate()繼承。如果您確信要手動編寫它,則可以將this.propsnextPropsthis.statenextState進行比較,並返回false以指示React更新可以跳過。

所以,如果你實現自己的shouldComponentUpdate它可能會覆蓋PureComponent的淺層比較

+4

我不認爲這是一個_probably_是OP在這裏尋找的! –

相關問題