Android 使用 React Navigation 5 进行深度链接

Android Deep Linking with React Navigation 5

我正在尝试将 Deep Linking in React Navigation 5 实现到我的 React Native 0.61 项目中,该项目是通过 react-native init 创建的。

当应用程序在后台时,深度 linking 工作。在我的 Android 设备上,我可以单击 https://myproject.com/content/5,应用程序会正确导航到内容部分并显示 ID 为 5 的内容。

但是,如果我终止该应用程序(或在不打开它的情况下安装它)并单击相同的 link,我将被带到主页,而不是导航到相应的内容页面。

我的activityAndroidManifest.xml:

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:launchMode="singleTask">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="http" />
        <data android:scheme="https" />
        <data android:host="myproject.com"/>
    </intent-filter>
</activity>

App.js的肉和土豆:

const config = {
  Content: {
    path: "content/:id",
    parse: {
      id: Number
    }
  }
};


const App = () => {
  const {state} = useContext(Context);
  const ref = React.useRef();

  const { getInitialState } = useLinking(ref, {
    prefixes: ['http://myproject.com'],
    config
  });

  const [isReady, setIsReady] = React.useState(false);
  const [initialState, setInitialState] = React.useState();

  useEffect(() => {
    Promise.race([
      getInitialState(),
      new Promise(resolve => setTimeout(resolve, 150)),
    ])
    .catch(e => {
      console.error(e);
    })
    .then(state => {
      if (state !== undefined) {
      setInitialState(state);
    }

    setIsReady(true);
    });
  }, [getInitialState]);

  return (
    <NavigationContainer initialState={initialState} ref={ref} >
      {state.isLoading || !isReady ? 
      (
        <Stack.Navigator screenOptions={{headerShown: false}}>
          <Stack.Screen name="Loading" component={LoadingScreen} />
        </Stack.Navigator>
      )
      :
      <MainStack />
      }
    </NavigationContainer>
  );
};

当 Android 用户使用深度 link 打开应用程序时,我应该怎么做才能让应用程序导航到内容页面,而应用程序之前已被杀死?

我还想保留当前的 ​​deep linking 行为,当应用程序在后台时,deep link 工作。

问题也得到了解释 here,但是 none 的建议解决方案对我有用。

您的导航器具有动态路由切换功能,因此您需要做的是先处理所有切换逻辑,然后在应用准备就绪后呈现导航器。目前,您的导航器会忽略 initialState 并且动态切换会覆盖呈现的路线。

尝试将您的加载状态移到导航器之外,或者确定应用程序已准备好在 effect 中显示导航器。