如何获取当前导航状态

新手上路,请多包涵

我正在使用来自 https://reactnavigation.org/docs/navigators/tab 的 React Navigation 的选项卡导航器,当我在选项卡屏幕之间切换时,我在 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
      }
    });

仪表板屏幕:

 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>
    );
  }
}

当它首先呈现组件时,我在仪表板屏幕上获得道具,但在切换选项卡时我没有得到道具。我需要获取当前的屏幕名称,即今天或本周。

原文由 Ahsan Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 388
1 个回答

您的问题与“屏幕跟踪”有关, react-navigation 对此有官方指南。您可以使用 onNavigationStateChange 通过内置导航容器跟踪屏幕,或者如果您想与 Redux 集成,可以编写一个 Redux 中间件来跟踪屏幕。更多详细信息可以在官方指南中找到: Screen-Tracking 。以下是使用 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);
      }
    }}
  />
);

原文由 ufxmeng 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题