【问题标题】:React-navigation navigate at startupReact-navigation 在启动时导航
【发布时间】:2020-09-21 22:49:27
【问题描述】:

我在我的应用中使用 react-navigation;我有一个这样的导航器:

const RootStack = createStackNavigator();

<RootStack.Navigator>
  <RootStack.Screen name="Main" component={Main} />
  <RootStack.Screen name="B" component={B} />
  <RootStack.Screen name="C" component={C} />
</RootStack.Navigator>

现在当应用程序启动时Main 将呈现;我正在使用 redux 操作获取一些数据,并且基于该数据,我可能必须将用户重定向到 C

所以在Main 组件中我只是在做

useEffect(() => {
  if (shouldRedirect)
    console.log('here')
    navigation.navigate('C')
  }
}, [shouldRedirect])

好吧,此时我可以在控制台中看到日志,但导航并没有发生; 我想这是因为有些东西还没有准备好,因为只需将navigate 包装在如下所示的超时中,就可以使其按预期工作:

useEffect(() => {
  if (shouldRedirect) {
    setTimeout(() => {
      navigation.navigate('C')
    }, 1)
  }
}, [shouldRedirect])

无论如何,这看起来是一个丑陋的解决方法;我想了解如何正确实施...

【问题讨论】:

    标签: react-native react-navigation


    【解决方案1】:

    您还应该将navigation 添加到您的依赖数组中:

    useEffect(() => {
      if (shouldRedirect)
        console.log('here')
        navigation.navigate('C')
      }
    }, [navigation, shouldRedirect])
    

    【讨论】:

    • 我最初接受了这个答案,因为当我尝试它时它似乎可以工作,但实际上这只是一个案例......我尝试了一个全新的应用程序来测试它而没有任何其他效果和添加此依赖项对我没有影响
    • 很抱歉,它不起作用。你能告诉我你正在使用哪个版本的@react-navigation/stack 吗?我根据您创建了一个基本示例,它立即成功导航到 C。如果您只是在一个空的依赖项 [] 中调用您的 navigation.navigate 而没有 shouldRedirect 条件语句(我的意思是纯 componentDidmount),会发生什么?
    • 你也可以尝试像这样使用initialRouteName:
    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 2018-04-08
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    相关资源
    最近更新 更多