Tracking screen transitions in React Navigation

Define the navigation stack to use

const RootStack = StackNavigator(
    // ... 略去具体内容
);

Tool method: Get the current screen name

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

Listen for screen changes on the used navigation stack

export default class App extends Component {
//... 其他代码

 render() {
        return (<RootStack  onNavigationStateChange={(prevState, currentState) => {
                const currentScreen = getCurrentRouteName(currentState);
                const prevScreen = getCurrentRouteName(prevState);
                if (prevScreen !== currentScreen) {
                    console.log("当前屏幕切换到了:" + currentScreen);
                }
            }}
        />);
    }

//... 其他代码
}

References

Screen Tracking

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325591366&siteId=291194637