blog icon indicating copy to clipboard operation
blog copied to clipboard

react-navigation 集成redux & 安卓返回 & 获得当前路由routeName

Open wuweijia opened this issue 7 years ago • 0 comments

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;

wuweijia avatar Dec 18 '17 03:12 wuweijia