react-navigation 路由级登录拦截

本文介绍了如何在React Navigation中设置路由状态改变拦截器,实现登录跳转拦截功能,确保未登录用户无法访问受保护的页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 路由栈

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值