react-navigation 路由级登录拦截

前端之家收集整理的这篇文章主要介绍了react-navigation 路由级登录拦截前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

// 路由栈

const Navigator =@H_403_5@ StackNavigator({ Setting: {screen: SettingSCreenView},.... });

1、设置路由状态改变拦截

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


class StartScreen extends Component {
    render() {
        const prefix = Platform.OS === @H_403_5@'android' ? @H_403_5@'xx://aa/' : @H_403_5@'xx://';
        return (
            <Navigator uriPrefix={prefix}
                onNavigationStateChange={
                    (prevState,currentState) => {
                        const currentScene = getCurrentRouteName(currentState);
                        if(currentScene == @H_403_5@'Setting'){
                        // to do something
                    }
                } 
            />);
    }

2、登录跳转拦截

// 拦截登录的路由
const needLoginRoute = [@H_403_5@'Setting'];

const defaultGetStateForAction = StartScreen.router.getStateForAction;

StartScreen.router.getStateForAction = (action,state) => {
    let routeName = dealMsgDeal(action.routeName);
    // 拦截需要登录跳转的也没
    if(action.routeName === routeName && islogin == false){
        this.routes = [
            ...state.routes,{key: @H_403_5@'id-'+Date.now(),routeName: @H_403_5@'Login',params: { name: routeName,params: action.params}},];
        return {
            ...state,routes,index: this.routes.length - 1,};
    }
    return defaultGetStateForAction(action,state);
};


// 需要拦截登录页面
function dealMsgDeal(routeName){
    let theRouteName = @H_403_5@'';
    if(routeName){
        for (var i in needLoginRoute) {
            if (needLoginRoute[i] == routeName) {
                theRouteName = routeName;
                break;
            }
        }
    }
    return theRouteName;
}

猜你在找的React相关文章