通过导航时无法获取参数

时间:2019-09-27 02:56:22

标签: javascript reactjs react-native react-navigation

我有两个导航器,一个AuthStackNavigator包含SignInScreen,一个AppBottomTabNavigator包含HomeScreen,我想从HomeScreen导航到SignInScreen,并传递一些参数来指示来源。

我尝试了很多类似以下的代码。

navigation.navigate('Auth', { source: 'App' })

navigation.navigate(
  'Auth',
  {},
  {
    type: 'Navigate',
    routeName: 'Auth',
    params: { source: 'App' }
  }
)

navigation.navigate(
  'Auth',
  {},
  {
    type: 'Navigate',
    routeName: 'Auth',
    action: {
      type: 'Navigate',
      routeName: 'SignInScreen',
      params: { source: 'App' }
    }
  }
)

...

但是它们都不起作用。 navigation.getParam('source', null)始终返回null。

更多信息 https://github.com/liudonghua123/expo-multi-screen-starter/blob/navigation_params_null/src/screens/HomeScreen.js#L22 https://github.com/liudonghua123/expo-multi-screen-starter/blob/navigation_params_null/src/screens/SignInScreen.js#L26

我还阅读了https://github.com/react-navigation/react-navigation/issues/143https://github.com/react-navigation/react-navigation/issues/1237

预期行为

  • 我希望代码navigation.getParam('source', null)返回实际的参数。

如何复制

我也将其发布在https://github.com/react-navigation/react-navigation/issues/6335上。

1 个答案:

答案 0 :(得分:0)

最后,我需要将代码还原为navigation.navigate('Auth', { source: 'App' })中的HomeScreen,然后可以获得类似以下代码的参数。

    const parent = navigation.dangerouslyGetParent();
    let source = null;
    if (parent && parent.state && parent.state.params) {
      ({ source } = parent.state.params);
    }