|
import type { NavigationAction, NavigationParams } from 'react-navigation'; |
|
|
|
import * as React from 'react'; |
|
import { BackHandler } from 'react-native'; |
|
import { NavigationActions, StackNavigator, addNavigationHelpers } from 'react-navigation'; |
|
import { action, observable } from 'mobx'; |
|
import { observer } from 'mobx-react'; |
|
|
|
const RootNavigator = StackNavigator( |
|
{ |
|
splash: { screen: SplashScreen }, |
|
login: { screen: LoginScreen }, |
|
}, |
|
); |
|
|
|
const rootRouter = RootNavigator.router; |
|
|
|
class $NavigationStore { |
|
@observable |
|
navigationState = rootRouter.getStateForAction( |
|
rootRouter.getActionForPathAndParams('splash'), |
|
); |
|
|
|
// it can be more helpers like this, for things like goBack, reset, etc. |
|
navigate = (routeName: string, params?: NavigationParams): void => |
|
this.dispatch(NavigationActions.navigate({ params, routeName })); |
|
|
|
@action |
|
dispatch = (dispatchedAction: NavigationAction) => { |
|
this.navigationState = rootRouter.getStateForAction( |
|
dispatchedAction, |
|
this.navigationState, |
|
); |
|
}; |
|
} |
|
|
|
export const NavigationStore = new $NavigationStore(); |
|
|
|
@observer |
|
class AppRouter extends React.Component<{}> { |
|
componentDidMount() { |
|
BackHandler.addEventListener('hardwareBackPress', this._onBackPress); |
|
} |
|
|
|
componentWillUnmount() { |
|
BackHandler.removeEventListener('hardwareBackPress', this._onBackPress); |
|
} |
|
|
|
_onBackPress = () => { |
|
if (NavigationStore.navigationState.index === 0) { |
|
return false; |
|
} |
|
|
|
NavigationStore.dispatch(NavigationActions.back()); |
|
return true; |
|
}; |
|
|
|
|
|
render() { |
|
return ( |
|
<RootNavigator |
|
navigation={addNavigationHelpers({ |
|
dispatch: NavigationStore.dispatch, |
|
state: toJS(NavigationStore.navigationState), |
|
})} |
|
/> |
|
); |
|
} |
|
} |
nice integration, I was wondering if you got this to work with the latest version of Mobx? Since the
navigation
object should now have the addEventListener field.