fix: show redbox instead of crash if navigation isn't initialized

This commit is contained in:
Satyajit Sahoo
2021-03-05 13:44:17 +01:00
parent 86e64fdcd8
commit 13d85530ae
2 changed files with 27 additions and 17 deletions

View File

@@ -141,10 +141,10 @@ const BaseNavigationContainer = React.forwardRef(
action: NavigationAction | ((state: NavigationState) => NavigationAction)
) => {
if (listeners.focus[0] == null) {
throw new Error(NOT_INITIALIZED_ERROR);
console.error(NOT_INITIALIZED_ERROR);
} else {
listeners.focus[0]((navigation) => navigation.dispatch(action));
}
listeners.focus[0]((navigation) => navigation.dispatch(action));
};
const canGoBack = () => {
@@ -168,15 +168,15 @@ const BaseNavigationContainer = React.forwardRef(
const target = state?.key ?? keyedListeners.getState.root?.().key;
if (target == null) {
throw new Error(NOT_INITIALIZED_ERROR);
console.error(NOT_INITIALIZED_ERROR);
} else {
listeners.focus[0]((navigation) =>
navigation.dispatch({
...CommonActions.reset(state),
target,
})
);
}
listeners.focus[0]((navigation) =>
navigation.dispatch({
...CommonActions.reset(state),
target,
})
);
},
[keyedListeners.getState, listeners.focus]
);

View File

@@ -683,11 +683,15 @@ it('throws if there is no navigator rendered', () => {
render(element);
act(() => {
expect(() => ref.current?.dispatch({ type: 'WHATEVER' })).toThrow(
"The 'navigation' object hasn't been initialized yet."
);
});
const spy = jest.spyOn(console, 'error').mockImplementation();
ref.current?.dispatch({ type: 'WHATEVER' });
expect(spy.mock.calls[0][0]).toMatch(
"The 'navigation' object hasn't been initialized yet."
);
spy.mockRestore();
});
it("throws if the ref hasn't finished initializing", () => {
@@ -703,9 +707,15 @@ it("throws if the ref hasn't finished initializing", () => {
const TestScreen = () => {
React.useEffect(() => {
expect(() => ref.current?.dispatch({ type: 'WHATEVER' })).toThrow(
const spy = jest.spyOn(console, 'error').mockImplementation();
ref.current?.dispatch({ type: 'WHATEVER' });
expect(spy.mock.calls[0][0]).toMatch(
"The 'navigation' object hasn't been initialized yet."
);
spy.mockRestore();
}, []);
return null;