feat: make actions work across navigators

This commit is contained in:
satyajit.happy
2019-06-11 13:01:03 +02:00
parent 14aa95515e
commit 5c6ec4e1f2
5 changed files with 116 additions and 38 deletions

View File

@@ -115,9 +115,18 @@ const StackRouter = {
case 'NAVIGATE':
if (state.names.includes(action.payload.name)) {
// If the route already exists, navigate to that
const index = state.routes.findIndex(
route => route.name === action.payload.name
);
let index = -1;
if (state.routes[state.index].name === action.payload.name) {
index = state.index;
} else {
for (let i = state.routes.length - 1; i >= 0; i--) {
if (state.routes[i].name === action.payload.name) {
index = i;
break;
}
}
}
if (index === -1) {
return StackRouter.reduce(state, {
@@ -161,13 +170,13 @@ const StackRouter = {
}
default:
return state;
return null;
}
},
actions: {
push(name: string): Action {
return { type: 'PUSH', payload: { name } };
push(name: string, params?: object): Action {
return { type: 'PUSH', payload: { name, params } };
},
pop(): Action {
return { type: 'POP' };

View File

@@ -139,11 +139,8 @@ const TabRouter = {
return null;
case 'GO_BACK':
return null;
default:
return state;
return null;
}
},

View File

@@ -6,6 +6,7 @@ import {
Screen,
CompositeNavigationProp,
TypedNavigator,
NavigationHelpers,
} from '../src';
import StackNavigator, { StackNavigationProp } from './StackNavigator';
import TabNavigator, { TabNavigationProp } from './TabNavigator';
@@ -34,7 +35,10 @@ const Tab: TypedNavigator<TabParamList, typeof TabNavigator> = {
const First = ({
navigation,
}: {
navigation: StackNavigationProp<StackParamList, 'first'>;
navigation: CompositeNavigationProp<
StackNavigationProp<StackParamList, 'first'>,
NavigationHelpers<TabParamList>
>;
}) => (
<div>
<h1>First, {navigation.state.params.author}</h1>
@@ -44,6 +48,9 @@ const First = ({
<button type="button" onClick={() => navigation.push('third')}>
Push third
</button>
<button type="button" onClick={() => navigation.navigate('fourth')}>
Navigate to fourth
</button>
<button
type="button"
onClick={() => navigation.navigate('first', { author: 'John' })}
@@ -59,7 +66,10 @@ const First = ({
const Second = ({
navigation,
}: {
navigation: StackNavigationProp<StackParamList, 'second'>;
navigation: CompositeNavigationProp<
StackNavigationProp<StackParamList, 'second'>,
NavigationHelpers<TabParamList>
>;
}) => (
<div>
<h1>Second</h1>