在 React Navigation TabNavigator 中动态设置 initialRouteName

Set initialRouteName dynamically in React Navigation TabNavigator

我想在启动画面中动态设置 TabNavigatorinitialRouteName。在 splash 中,我根据 api 结果决定 initialRouteName,但我不知道如何将此路由名称传递到我的路由器文件。

Router.tsx:

public static Routes = StackNavigator({
    Splash: { screen: Splash },
    Verification: { screen: Verification },
    Login: { screen: Login },
    Main: {
        screen: TabNavigator({
            Calendar: { screen: Calendar },
            PendingReserves: { screen: PendingReserves },
            Profile: { screen: Profile },
        }, 
        {initialRouteName: 'Calendar'}) // I want to set it from splash
    }        
}, {initialRouteName: 'Splash'} );

splash.tsx:

constructor(props: SplashScreenProps, context: any) {
    super(props, context);
    this.state = {
        Error: false
    }
    this.check()
}

check = async () => {
    let pending = await dataService.getPendingReserves(data);
    if (pending.Success) {                
        if (pending.result.length > 0) {
            // go to pendingReserve Tab
        } else {
            // go to Calendar Tab
        }
    } else {
        this.setState({ Error: true })
    }
}

我尝试静态路由到 PendingReserves 并在其构造函数中检查 api 并在必要时更改选项卡,但我无法使用以下代码以编程方式更改选项卡:

pendingReserves.tsx:

fetchData = async () => {
    let res = await Utilities.getPendingReserves()
    if (res && res.length > 0) {
        ...
    } else {
        const resetAction = NavigationActions.reset({
            index: 0,
            actions: [NavigationActions.navigate({ routeName: 'Calendar' })]
        })
        this.props.navigation.dispatch(resetAction)
        // this.props.navigation.navigate({ routeName: 'Calendar' })
        // both reset and simple navigate are not works correctly... 
    }
}

因此,任何动态设置 initialRouteName 或以编程方式更改选项卡的解决方案都会对我有所帮助。谢谢

我正在使用:

"react-native": "0.49.3",
"react-navigation": "^1.0.0-beta.13"

最后...我没有找到在 react navigation 版本 1 中以编程方式更改选项卡的方法,所以我更新到版本 2 并且 this.props.navigation.navigate('Calendar') 可以正常工作。