首页 > 解决方案 > 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-nativereact-navigation

解决方案


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

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

推荐阅读