reactjs – 如何获取当前导航状态

前端之家收集整理的这篇文章主要介绍了reactjs – 如何获取当前导航状态前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我从 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
      }
    });

仪表板屏幕:

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

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

你的问题是关于“屏幕跟踪”,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);
      }
    }}
  />
);
原文链接:https://www.f2er.com/react/300942.html

猜你在找的React相关文章