使用StackNavigator.router.getStateForAction
來操縱你的路由狀態。
//assume your StackNavigator1 just like below
const StackNavigator1 = new StackNavigator({
Screen1: {screen: Screen1},
Screen2: {screen: Screen2},
Screen3: {screen: Screen3},
Screen4: {screen: Screen4},
Screen5: {screen: Screen5}
});
const defaultGetStateForAction = StackNavigator1.router.getStateForAction;
//store the state when navigate to screen3
let state3;
StackNavigator1.router.getStateForAction = (action, state) => {
let newState = defaultGetStateForAction(action, state);
//print out the state object
console.log(`newState: ${newState}`);
//change all the routeName 'Screen3', 'Screen4' to match your own project
if (action.type === 'Navigation/NAVIGATE' && action.routeName === 'Screen3') {
//store the state of screen3 for restore it later
state3 = newState;
}
if (action.type === 'Navigation/NAVIGATE' && action.routeName === 'Screen4') {
//check if screen3 exist in the state, change the condition for your own need
let result = newState.routes.find((route) => {
return route.routeName === 'Screen3'
});
//if 'screen3' doesn't exist, add it to the route manually
if (result === undefined && state3 !== undefined) {
let route4 = newState.routes[newState.index];
let routes = state3.routes.slice();
routes.push(route4);
return {index: 3, routes}
}
}
return defaultGetStateForAction(action, state)
};
//... the rest code