react-navigation
是提供了goBack()到指定頁面的方法的,那就是在goBack()中添加一個參數,但當你使用goBack('Main')
的時候,你會發現並無跳轉,緣由是react-navigation默認goBack()中的參數是系統隨機分配的key
,而不是手動設置的routeName
,而方法內部又沒有提供能夠得到key
的方法,因此這裏只能經過修改源碼將key
換成routeName
了。
下面的內容直接引用了hello老文
的內容javascript
把項目/node_modules/react-navigation/src/routers/StackRouter.js文件裏的
const backRoute = state.routes.find((route: *) => route.key === action.key);
改爲 const backRoute = state.routes.find(route => route.routeName === action.key);
但不是很完美, 這裏的component要填想返回的組件的前一個組件的routeName, 好比你的棧裏順序是home1, home2, home3, home4, 在home4裏要返回home2, 使用this.props.navigation.goBack('home3');; 而且又會帶出一個問題: goBack()方法沒反應了, 必須加個null進去, 寫成goBack(null)...
if (action.type === NavigationActions.BACK) { let backRouteIndex = null; if (action.key) { const backRoute = state.routes.find( /* $FlowFixMe */ /* 修改源碼 */ route => route.routeName === action.key /* (route: *) => route.key === action.key */ ); /* $FlowFixMe */ console.log('backRoute =====',backRoute); backRouteIndex = state.routes.indexOf(backRoute); console.log('backRoute =====',backRouteIndex); } if (backRouteIndex == null) { return StateUtils.pop(state); } if (backRouteIndex >= 0) { return { ...state, routes: state.routes.slice(0, backRouteIndex+1), index: backRouteIndex - 1 + 1, }; } }