如何获取当前导航状态

Ahs*_*Ali 8 reactjs react-native react-redux react-navigation

我正在使用来自https://reactnavigation.org/docs/navigators/tab的 React Navigation的Tab Navigator ,当我在Tab屏幕之间切换时,我在this.props.navigation中没有获得任何导航状态.

标签导航器:

    import React, { Component } from 'react';
    import { View, Text, Image} from 'react-native';
    import DashboardTabScreen from 'FinanceBakerZ/src/components/dashboard/DashboardTabScreen';
    import { TabNavigator } from 'react-navigation';


       render() {
        console.log(this.props.navigation);   

        return (
          <View>
              <DashboardTabNavigator  />
          </View>
        );
      }



    const DashboardTabNavigator = TabNavigator({
      TODAY: {
        screen: DashboardTabScreen
      },
      THISWEEK: {
        screen: DashboardTabScreen
      }
    });
Run Code Online (Sandbox Code Playgroud)

仪表板屏幕:

import React, { Component } from 'react';
import { View, Text} from 'react-native';

export default class DashboardTabScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {};
    console.log('props', props);

  }

  render() {
    console.log('props', this.props);
    return (
      <View style={{flex: 1}}>
        <Text>Checking!</Text>
      </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我在仪表板屏幕上获得道具时首先渲染组件,但是当我切换标签时我没有得到道具.我需要获取当前的屏幕名称,即TODAY或THISWEEK.

ufx*_*eng 11

你的问题是关于"屏幕跟踪",react-navigation有一个官方指南.您可以使用onNavigationStateChange内置导航容器来跟踪屏幕,或者如果要与Redux集成,可以编写Redux中间件来跟踪屏幕.更多细节可以在官方指南中找到:屏幕跟踪.以下是指南中的示例代码onNavigationStateChange:

import { GoogleAnalyticsTracker } from 'react-native-google-analytics-bridge';

const tracker = new GoogleAnalyticsTracker(GA_TRACKING_ID);

// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
  if (!navigationState) {
    return null;
  }
  const route = navigationState.routes[navigationState.index];
  // dive into nested navigators
  if (route.routes) {
    return getCurrentRouteName(route);
  }
  return route.routeName;
}

const AppNavigator = StackNavigator(AppRouteConfigs);

export default () => (
  <AppNavigator
    onNavigationStateChange={(prevState, currentState) => {
      const currentScreen = getCurrentRouteName(currentState);
      const prevScreen = getCurrentRouteName(prevState);

      if (prevScreen !== currentScreen) {
        // the line below uses the Google Analytics tracker
        // change the tracker here to use other Mobile analytics SDK.
        tracker.trackScreenView(currentScreen);
      }
    }}
  />
);
Run Code Online (Sandbox Code Playgroud)


vin*_*nod 6

首先检查所有属性,比如

<Text>{JSON.stringify(this.props, null, 2)}</Text>
Run Code Online (Sandbox Code Playgroud)

上面的json数组将显示routeName index下的当前导航状态ie

this.props.navigation.state.routeName
Run Code Online (Sandbox Code Playgroud)