blog
blog copied to clipboard
react-navigation 集成redux & 安卓返回 & 获得当前路由routeName
import React, { PropTypes, Component } from 'react';
import { BackHandler } from 'react-native';
import { connect } from 'react-redux';
import { addNavigationHelpers, NavigationActions } from 'react-navigation';
import NavigationStack from '../../router';
@connect(state => ({
navigationState: state.navigationState,
}))
class AppNavigation extends Component {
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
onBackPress = () => {
const { dispatch, navigationState } = this.props;
if (navigationState.index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
};
render() {
const { dispatch, navigationState } = this.props;
let routeName;
if (navigationState.routes[navigationState.index].routes) {
const tabRoutes = navigationState.routes[navigationState.index];
routeName = tabRoutes.routes[tabRoutes.index].routeName;
} else {
routeName = navigationState.routes[navigationState.index].routeName;
}
return (
<NavigationStack
screenProps={{ currentRouteName: routeName }}
navigation={addNavigationHelpers({ dispatch, state: navigationState })}
/>
);
}
}
AppNavigation.propTypes = {
navigationState: PropTypes.object,
dispatch: PropTypes.func,
};
export default AppNavigation;