react-navigation goBack()传参返回无效

项目中使用react-navigation,返回方法this.props.navigation.goBack('Login');点击按钮怎么没返回呢?

原因剖析

看了下react-navigation源码发现了问题:goBack(key),方法中传的参数不是用自定义的routeName而是用自动生成的随机值key。
如果传Login界面的key值过去,发现源码中并没有对backRouteIndex为0的情况进行处理,导致其不能返回到根界面。

思路

现在能想到的思路就是将根界面的key保存下来,在需要跳转根界面时将key值传到GoBack()中。

操作步骤

找到react-navigation中的StackRouter.js文件,将源码中关键步骤的值用log打印出来:

if (action.type === NavigationActions.BACK) {
        let backRouteIndex = null;
        if (action.key) {
            console.log('---------------action.key=',action.key);
          const backRoute = state.routes.find(
            /* $FlowFixMe */
            // (route: *) => route.key === action.key
            (route) => route.key === action.key
        );
            console.log('---------------backRoute=',backRoute);
            console.log('---------------routes=',state.routes);

            /* $FlowFixMe */
          backRouteIndex = state.routes.indexOf(backRoute);
            console.log('---------------backRouteIndex=',backRouteIndex);

        }
        if (backRouteIndex == null) {
          return StateUtils.pop(state);
        }
        if (backRouteIndex > 0) {
            console.log('-----------------return>0--',state);
          return {
            ...state,
            routes: state.routes.slice(0, backRouteIndex),
            index: backRouteIndex - 1,
          };
        }
      }
      return state;
    },

goBack()打印log:

在源码中添加对backRouteIndex=0的处理:

       if(backRouteIndex === 0) {
            console.log('-----------------return=0--',state);
            return {
                ...state,
                routes: state.routes.slice(0),
                index: backRouteIndex,
            };
        }

传参返回打印log:

这样就可以跳转到根界面了~

注:这样只是添加了backRouteIndex=0的处理,goBack()所传参数仍是随机生成的key,并非routeName。

要想可以使用this.props.navigation.goBack('Login');返回还需改动源码,但这样修改还会有小问题,详见文章react-navigation中的goBack()问题。

       if (action.key) {          
            const backRoute = state.routes.find(
            /* $FlowFixMe */
            // (route: *) => route.key === action.key
            (route) => route.routeName === action.key
        );

若有好的解决方法,希望大家多多评论~共同探讨!

你可能感兴趣的:(react-navigation goBack()传参返回无效)