初學React高階函數

React和高階函數的定義就不說了,主要是記錄下小白看react庫時大佬用高階組件時看不懂的地方。react

export const createCesiumComponent = <E, P, C, CC = {}, R = {}>(
  opts: CesiumComponentOption<E, P, C, CC, R>,
): CesiumComponentType<E, P, C> => {
  class CesiumComponent extends React.PureComponent<WithContextProps<P, C>> {
    ......
}

先看 class CesiumComponent extends React.PureComponent<WithContextProps<P,C>>segmentfault

React.PureComponent 與 React.Component 幾乎徹底相同,但 React.PureComponent 經過prop和state的淺對比來實現 shouldComponentUpate()。
若是React組件的 render() 函數在給定相同的props和state下渲染爲相同的結果,在某些場景下你能夠使用 React.PureComponent 來提高性能。
React.PureComponent 的 shouldComponentUpdate() 只會對對象進行淺對比。若是對象包含複雜的數據結構,它可能會因深層的數據不一致而產生錯誤的否認判斷(表現爲對象深層的數據已改變視圖卻沒有更新, 原文:false-negatives)。當你指望只擁有簡單的props和state時,纔去繼承 PureComponent ,或者在你知道深層的數據結構已經發生改變時使用 forceUpate() 。或者,考慮使用 不可變對象 來促進嵌套數據的快速比較。
此外,React.PureComponent 的 shouldComponentUpate() 會忽略整個組件的子級。請確保全部的子級組件也是」Pure」的。

原文連接
PureComponent理解了,看Context,withContext,涉及
Context 提供了一種在組件之間共享此類值的方式,而沒必要經過組件樹的每一個層級顯式地傳遞 props
接着看CesiumComponentOption接口數據結構

export interface CesiumComponentOption<E, P, C, CC = {}, R = {}> {
  name: string;
  create: (
    cesiumProps: Readonly<P>,
    props: Readonly<P>,
    context: Readonly<C>,
    ref?: React.RefObject<R>,
  ) => E | [E, any];
  mount?: (element: E, context: Readonly<C>, props: Readonly<P>, ref?: React.RefObject<R>) => void;
  unmount?: (
    element: E,
    context: Readonly<C>,
    props: Readonly<P>,
    ref: React.RefObject<R> | undefined,
    state: any,
  ) => void;
  render?: (
    element: E | undefined,
    props: Readonly<P> & Readonly<{ children?: React.ReactNode }>,
    mounted: boolean,
    ref: React.RefObject<R> | undefined,
  ) => React.ReactNode;
  update?: (element: E, props: Readonly<P>, prevProps: Readonly<P>, context: Readonly<C>) => void;
  provide?: (element: E, props: Readonly<P>, state: any) => CC;
  cesiumProps?: (keyof P)[];
  cesiumReadonlyProps?: (keyof P)[];
  cesiumEventProps?: EventkeyMap<E, keyof P>;
  setCesiumPropsAfterCreate?: boolean;
  noRender?: boolean;
  createRef?: boolean;
  defaultProps?: Partial<P>;
}

看這個ide

cesiumProps: Readonly<P>,
    props: Readonly<P>,
    context: Readonly<C>,
    ref?: React.RefObject<R>,

泛型大概知道了,看create,mount,unmount,update,這看起來是定義了生命週期。
後面就不用看了,大概就是有這樣的一個組件:Clock,它是經過高階組件createCesiumComponent建立的,高階組件在Clock自己有的
componentDidMount,componentDidUpdate,componentWillUnmount中加了料,又封裝了一套生命週期。
後面的看懂了再分享。函數

相關文章
相關標籤/搜索