react-navigation 路由级登录拦截

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

// 路由栈

const Navigator = 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 === 'android' ? 'xx://aa/' : 'xx://';
        return (
            <Navigator uriPrefix={prefix}
                onNavigationStateChange={
                    (prevState,currentState) => {
                        const currentScene = getCurrentRouteName(currentState);
                        if(currentScene == 'Setting'){
                        // to do something
                    }
                } 
            />);
    }

2、登录跳转拦截

// 拦截登录的路由
const needLoginRoute = ['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: 'id-'+Date.now(),routeName: 'Login',params: { name: routeName,params: action.params}},];
        return {
            ...state,routes,index: this.routes.length - 1,};
    }
    return defaultGetStateForAction(action,state);
};


// 需要拦截登录页面
function dealMsgDeal(routeName){
    let theRouteName = '';
    if(routeName){
        for (var i in needLoginRoute) {
            if (needLoginRoute[i] == routeName) {
                theRouteName = routeName;
                break;
            }
        }
    }
    return theRouteName;
}
原文链接:https://www.f2er.com/react/301720.html

猜你在找的React相关文章