import React , { Component } from 'react' ; import { withRouter , RouteComponentProps } from 'react-router-dom' ; import { FC } from '../interface/fc' ; let _this = null ; let routerChanged = false ; const popStateFn = ( e ) => { routerChanged = true ; if ( ! location . hash && _this && _this . getInitialProps ) { _this . getInitialProps ( ) ; } } ; interface IState { extraProps : Object ; } function GetInitialProps ( WrappedComponent ) { class GetInitialPropsClass extends Component < RouteComponentProps < { } > , IState > { constructor ( props ) { super ( props ) ; this . state = { extraProps : { } } ; if ( ! routerChanged ) { routerChanged = ! window . __USE_SSR__ || ( props . history && props . history . action === 'PUSH' ) ; } if ( window . __USE_SSR__ ) { _this = this ; window . addEventListener ( 'popstate' , popStateFn ) ; } } async componentDidMount ( ) { if ( ( this . props . history && this . props . history . action !== 'POP' || ! window . __USE_SSR__ ) ) { await this . getInitialProps ( ) ; } } async getInitialProps ( ) { const props = this . props ; if ( WrappedComponent . preload ) { WrappedComponent = ( await WrappedComponent . preload ( ) ) . default ; } const extraProps = WrappedComponent . getInitialProps ? await WrappedComponent . getInitialProps ( props ) : { } ; this . setState ( { extraProps } ) ; } render ( ) { return < WrappedComponent { ... Object . assign ( { } , this . props , routerChanged ? { } : window . __INITIAL_DATA__ , this . state . extraProps ) } / > ; } } return withRouter ( GetInitialPropsClass ) ; } export default GetInitialProps ;