import { SHOW , HIDE , MINIAPP_PAGE_LIFECYCLE } from '../constants' ; type UseEffect = ( effect : React . EffectCallback , deps ? : React . DependencyList ) => void ; type Listener = ( ) => any ; function addPageLifeCycle ( cycle , callback ) { document . addEventListener ( MINIAPP_PAGE_LIFECYCLE [ cycle ] , callback ) ; } function createPageLifeCycle ( useEffect ) { return ( cycle , callback ) => { useEffect ( ( ) => { if ( cycle === SHOW ) { callback ( ) ; } addPageLifeCycle ( cycle , callback ) ; return ( ) => { document . removeEventListener ( MINIAPP_PAGE_LIFECYCLE [ cycle ] , callback ) ; } ; } , [ ] ) ; } ; } export function withPageLifeCycle < P > ( Component ) { class Wrapper extends Component { private onShow : ( ) => void ; private onHide : ( ) => void ; private pathname : string ; constructor ( props , context ? ) { super ( props , context ) ; if ( this . onShow ) { addPageLifeCycle ( SHOW , this . onShow . bind ( this ) ) ; } if ( this . onHide ) { addPageLifeCycle ( HIDE , this . onHide . bind ( this ) ) ; } } public componentWillUnmount ( ) { super . componentWillUnmount ?. ( ) ; } } Wrapper . displayName = `withPageLifeCycle(${ Component . displayName || Component . name })` ; return Wrapper as React . ComponentClass ; } export function createUsePageLifeCycle ( { useEffect } ) { const usePageShow = ( callback ) => { createPageLifeCycle ( useEffect ) ( SHOW , callback ) ; } ; const usePageHide = ( callback ) => { createPageLifeCycle ( useEffect ) ( HIDE , callback ) ; } ; return { usePageShow , usePageHide } ; }