1 | import { getActionFromState, getStateFromPath, NavigationContainerRefContext } from '@react-navigation/core';
|
2 | import * as React from 'react';
|
3 | import LinkingContext from './LinkingContext';
|
4 | export default function useLinkTo() {
|
5 | const navigation = React.useContext(NavigationContainerRefContext);
|
6 | const linking = React.useContext(LinkingContext);
|
7 | const linkTo = React.useCallback(to => {
|
8 | if (navigation === undefined) {
|
9 | throw new Error("Couldn't find a navigation object. Is your component inside NavigationContainer?");
|
10 | }
|
11 |
|
12 | if (typeof to !== 'string') {
|
13 |
|
14 | navigation.navigate(to.screen, to.params);
|
15 | return;
|
16 | }
|
17 |
|
18 | if (!to.startsWith('/')) {
|
19 | throw new Error(`The path must start with '/' (${to}).`);
|
20 | }
|
21 |
|
22 | const {
|
23 | options
|
24 | } = linking;
|
25 | const state = options !== null && options !== void 0 && options.getStateFromPath ? options.getStateFromPath(to, options.config) : getStateFromPath(to, options === null || options === void 0 ? void 0 : options.config);
|
26 |
|
27 | if (state) {
|
28 | const action = getActionFromState(state, options === null || options === void 0 ? void 0 : options.config);
|
29 |
|
30 | if (action !== undefined) {
|
31 | navigation.dispatch(action);
|
32 | } else {
|
33 | navigation.reset(state);
|
34 | }
|
35 | } else {
|
36 | throw new Error('Failed to parse the path to a navigation state.');
|
37 | }
|
38 | }, [linking, navigation]);
|
39 | return linkTo;
|
40 | }
|
41 |
|
\ | No newline at end of file |